This is machine translation

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

Note: This page has been translated by MathWorks. Click here to see
To view all translated materials including this page, select Country from the country navigator on the bottom of this page.


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 function, unlike the throwAsCaller and rethrow functions, creates the stack trace from the location where MATLAB calls the function.

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


collapse all

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.

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 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.

Introduced in R2007b