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