Main Content

throw

Throw exception

Description

example

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.

Examples

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);
    throw(ME)
end

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 and throws an MException object.

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.

Extended Capabilities

Thread-Based Environment
Run code in the background using MATLAB® backgroundPool or accelerate code with Parallel Computing Toolbox™ ThreadPool.

Version History

Introduced in R2007b