This is machine translation

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


Class: MException

Throw exception




throw(exception) throws an exception based on the information contained in the MException object, exception. The exception terminates the currently running function and returns control either to the keyboard or to an enclosing catch block. When you throw an exception from outside a try/catch statement, MATLAB® displays the error message in the Command Window.

The throw method, unlike the throwAsCaller and rethrow methods, creates the stack trace from the location where MATLAB executes the method.

You can access the MException object via a try/catch statement or the MException.last method.

Input Arguments

expand all

exception — Exception containing cause and location of errorMException object

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


expand all

Create and Throw MException Object

Throw an exception if an input variable name does not exist in the workspace.

str = input('Type a variable name: ','s');
if ~exist(str,'var')
    ME = MException('MyComponent:noSuchVariable', ...
        'Variable %s not found',str);

At the input prompt, enter any variable that does not exist in your workspace. For example, enter notaVariable.

Variable notaVariable not found

Since notVariable doesn't exist in your workspace, MATLAB creates an MException object, and then throws it.

Compare Behavior of throw and rethrow

Create a function, combineArrays, in your working folder.

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

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

Call the combineArrays function with arrays of different sizes.

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

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.

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?