Documentation

This is machine translation

Translated by Microsoft
Mouseover text to see original. Click the button below to return to the English verison of the page.

Note: This page has been translated by MathWorks. Please click here
To view all translated materals including this page, select Japan from the country navigator on the bottom of this page.

rethrow

Class: MException

Rethrow previously caught exception

Syntax

rethrow(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. End the catch block with a rethrow statement to terminate the program and redisplay the exception.

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

Input Arguments

expand all

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

Examples

expand 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 (line 5)
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 (line 10)
V = cat(1,V1,V2);                % Line 10

Error in combineArrays (line 3)
    C = catAlongDim1(A,B);       % Line 3

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

Introduced in R2007b

Was this topic helpful?