rethrow - Rethrow previously caught exception - MATLAB (original) (raw)
Main Content
Rethrow previously caught exception
Syntax
Description
rethrow([exception](#budq1y%5F-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 thecatch
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.
Examples
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.
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
Exception containing the cause and location of an error, specified as a scalar MException
object.
Version History
Introduced in R2007b