Main Content

rethrow

Rethrow previously caught exception

Description

rethrow(exception) rethrows a previously caught exception, exception. MATLAB® typically responds to errors by terminating the currently running program. However, you can use a try/catch block to catch the exception. This interrupts the program termination so you can execute your own error handling procedures. To terminate the program and redisplay the exception, end the catch block with a rethrow statement.

rethrow handles the stack trace differently from error, assert, and throw. Instead of creating the stack from where MATLAB executes the function, rethrow preserves the original exception information and enables you to retrace the source of the original error.

example

Examples

collapse all

Cause MATLAB to throw an error by calling surf with no inputs. Catch the exception, display the error identifier, and rethrow the exception.

try
    surf
catch ME
    disp(['ID: ' ME.identifier])
    rethrow(ME)
end
ID: MATLAB:narginchk:notEnoughInputs
Error using surf (line 49)
Not enough input arguments.

Create a function, combineArrays, in your working folder.

function C = combineArrays(A,B)
try
    C = catAlongDim1(A,B);       % Line 3
catch exception
    throw(exception)             % Line 5
end
end

function V = catAlongDim1(V1,V2)
V = cat(1,V1,V2);                % Line 10
end

Call the combineArrays function with arrays of different sizes.

A = 1:5;
B = 1:4;

combineArrays(A,B)
Error using combineArrays
Dimensions of matrices being concatenated are not consistent.

The stack refers to line 5 where MATLAB throws the exception.

Replace throw(exception) with rethrow(exception) on line 5 of the combineArrays function, and call the function again.

combineArrays(A,B)
Error using cat
Dimensions of matrices being concatenated are not consistent.

Error in combineArrays>catAlongDim1
V = cat(1,V1,V2);       

Error in combineArrays
    C = catAlongDim1(A,B);      

The rethrow function maintains the original stack and indicates the error is on line 3.

Input Arguments

collapse all

Exception containing the cause and location of an error, specified as a scalar MException object.

Version History

Introduced in R2007b