Documentation

throwAsCaller

Class:MException

Throw exception as if occurs within calling function

Syntax

throwAsCaller(exception)

Description

throwAsCaller(异常)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 enclosingcatchblock. When you throw an exception from outside atry/catchstatement, MATLAB®displays the error message in the Command Window.

You can access theMException对象通过一个try/catchstatement or theMException.lastmethod.

In some cases, 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 usethrowAsCallerto simplify the error display.

Input Arguments

expand all

Exception containing the cause and location of an error, specified as a scalarMExceptionobject.

Examples

expand all

Create a function,sayHello, in your working folder.

functionsayHello(N) checkInput(N) str = ['Hello, 'N'!']; disp(str)functioncheckInput(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.

sayHello(42)
Error using sayHello>checkInput (line 9) Input must be char. Error in sayHello (line 2) 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.

Replacethrow(ME)withthrowAsCaller(ME)in line 9 ofsayHello.mand call the function again.

sayHello(42)
Error using sayHello (line 2) 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.

Introduced in R2007b

Was this topic helpful?