throwAsCaller - Throw exception as if occurs within calling function - MATLAB (original) (raw)
Main Content
Throw exception as if occurs within calling function
Syntax
Description
Note
In R2022b: throw is recommended overthrowAsCaller
because it creates the stack trace from the location where MATLABĀ® calls the function.
throwAsCaller([exception](#bud2010-exception))
throws an exception as if it occurs within the calling function. The exception terminates the currently running function and returns control to the keyboard or an enclosingcatch
block. When you throw an exception from outside atry/catch
statement, MATLAB displays the error message in the Command Window.
You can access the MException
object via atry/catch
statement or theMException.last
function.
Sometimes, it is more informative for the error to point to the location in the calling function that results in the exception rather than pointing to the function that actually throws the exception. You can use throwAsCaller
to simplify the error display.
Examples
Create a function, sayHello
, in your working folder.
function sayHello(N) checkInput(N) str = ['Hello, ' N '!']; disp(str)
function checkInput(N) if ~ischar(N) ME = MException('sayHello:inputError','Input must be char.'); throw(ME) end
At the command prompt, call the function with a numeric input.
Error using sayHello>checkInput Input must be char.
Error in sayHello checkInput(N)
The top of the stack refers to line 9 because this is where MATLAB throws the exception. After the initial stack frame, MATLAB displays information from the calling function.
Replace throw(ME)
withthrowAsCaller(ME)
in line 9 ofsayHello.m
and call the function again.
Error using sayHello Input must be char.
The top of the stack refers to line 2 because that is the location of the error in the calling function.
Input Arguments
Exception containing the cause and location of an error, specified as a scalar MException
object.
Extended Capabilities
Version History
Introduced in R2007b