MException
Capture error information
Description
Any MATLAB® code that detects an error and throws an exception constructs an
MException
object. The MException
object contains retrievable
information about errors. MATLAB can throw either predefined exceptions or exceptions that you
construct.
Creation
Description
Input Arguments
errID
— Identifier for error
character vector | string scalar
Identifier for the error, specified as a character vector or string scalar. Use the error identifier with exception handling to better identify the source of the error or to control a selected subset of the exceptions in your program.
The error identifier includes one or more component fields
and a mnemonic field. Fields must be separated with colon. For
example, an error identifier with a component field component
and a
mnemonic field mnemonic
is specified as
'component:mnemonic'
.
A component field typically specifies the product or functionality under which various errors can be generated. For example, the error identifier
'MATLAB:TooManyInputs'
has a component fieldMATLAB
, which means that the exception is thrown in MATLAB. You can reuse the same mnemonicTooManyInputs
as long as you precede it with different components. For example, if you want to throw an exception in your toolbox whenever a function is called with too many inputs, you can use'MyToolbox:TooManyInputs'
.The mnemonic field of an error identifier is typically a tag specific to the error issue. For example, when reporting an error resulting from the use of ambiguous syntax in MATLAB, you can specify the error identifier as
'MATLAB:ambiguousSyntax'
.
The component and mnemonic fields must each begin with a letter. The remaining
characters can be alphanumerics (A–Z, a–z, 0–9) and underscores. No white space
characters can appear in errID
.
Example: 'MyComponent:noSuchVariable'
Example: 'Simulink:Signals:InvalidNumberOfPorts'
msg
— Information about cause of error
character vector | string scalar
Information about the cause of the error and how you might correct it, specified
as a character vector or string scalar. To format the text, use escape sequences, such
as \t
or \n
. You also can use any format
specifiers supported by the sprintf
function, such as
%s
or %d
. Specify values for the conversion
specifiers using the A
input arguments.
Example: 'Error opening file.'
Example: 'Error on line %d.'
A1,...,An
— Replacement value
character vector | string scalar | numeric scalar
One or more values that replace the conversion specifiers in
msg
, each value is specified as a character vector, string
scalar, or numeric scalar.
Properties
identifier
— Unique identifier of error
character vector
This property is read-only.
Character vector that uniquely identifies the error, specified as a character vector
by the errID
input argument.
Example: 'MATLAB:test'
message
— Error message
character vector
This property is read-only.
Character vector that contains the error message that is displayed when MATLAB throws the exception, specified by the msg
and
A
input arguments.
Example: 'Variable x not found'
stack
— Stack trace information
structure array
This property is read-only.
Structure array that contains stack trace information including the file name
(file
), function name (name
), and line number
(line
) where MATLAB throws the exception. If the error occurs in a called function, the
stack
property also contains the file name, function name, and
line number for each of the called functions. MATLAB generates the stack only when it throws the exception.
stack
is an N-by-1 struct
array, where N represents the depth of the call stack.
cause
— Cause of exception
cell array of MException
objects
This property is read-only.
Cell array of MException
objects that caused MATLAB to create the exception. Use the addCause
method to add
an exception to the cause
property.
Correction
— Suggested fix for exception
matlab.lang.correction.AppendArgumentsCorrection
object | matlab.lang.correction.ConvertToFunctionNotationCorrection
object | matlab.lang.correction.ReplaceIdentifierCorrection
object
This property is read-only.
Suggested fix for the exception, specified as a matlab.lang.correction.AppendArgumentsCorrection
, matlab.lang.correction.ConvertToFunctionNotationCorrection
, or matlab.lang.correction.ReplaceIdentifierCorrection
object. When an exception
is thrown and not caught, MATLAB uses the Correction
property to suggest a fix for the
exception.
Object Functions
throw | Throw exception |
MException.last | Return last uncaught exception |
rethrow | Rethrow previously caught exception |
throwAsCaller | Throw exception as if occurs within calling function |
addCause | Record additional causes of exception |
addCorrection | Provide suggested fix for exception |
getReport | Get error message for exception |
Examples
Create MException Object
Create an MException
object to capture information about an input error.
errID = 'myComponent:inputError'; msgtext = 'Input does not have the expected format.'; ME = MException(errID,msgtext)
ME = MException with properties: identifier: 'myComponent:inputError' message: 'Input does not have the expected format.' cause: {} stack: [0x1 struct] Correction: []
Create MException with Formatted Error Message
Use both the msgtext
and A1,...,An
input arguments to create an error message.
errID = 'MATLAB:test'; msgtext = 'There are %d errors on this page'; A1 = 10; ME = MException(errID,msgtext,A1)
ME = MException with properties: identifier: 'MATLAB:test' message: 'There are 10 errors on this page' cause: {} stack: [0x1 struct] Correction: []
Create and Throw MException Object
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.
Access Information in MException Object
Use try, catch
to access the information
captured in an MException
object.
Create a file myfile.m
that contains a call to the surf
function with no inputs. (This function call results in an exception
and is intended for illustrative purposes.) Catch the exception that MATLAB throws in an MException
object ME
, and
display the error message by accessing the message
property of
ME
.
try surf catch ME disp('Error Message:') disp(ME.message) end
Error Message: Not enough input arguments.
Extract the error identifier.
ME.identifier
ans = 'MATLAB:narginchk:notEnoughInputs'
Query the contents of the stack
property. In this example, the
call stack is represented as a 2-by-1 structure array.
for i = 1:numel(ME.stack) ME.stack(i) end
ans = struct with fields: file: 'matlabroot\toolbox\matlab\graph3d\surf.m' name: 'surf' line: 49 ans = struct with fields: file: 'c:\myMATLABfiles\myfile.m' name: 'myfile' line: 2
The first element of stack
displays the file name
(surf.m
), function name (surf
), and line number
(49
) where the exception occurred. The second element of
stack
shows the name and line number where an exception occurred in
the caller script.
Respond to Thrown Exception
Catch the exception generated by calling a nonexistent function,
notaFunction
. If the function is not defined, issue a warning and
assign the output a value of 0.
try a = notaFunction(5,6); catch ME if strcmp(ME.identifier,'MATLAB:UndefinedFunction') warning('Function is undefined. Assigning a value of 0.'); else rethrow(ME) end end
Warning: Function is undefined. Assigning a value of 0.
By itself, the call to notaFunction
results in an error. Using
try
and catch
, this code catches the undefined
function exception and repackages it as a warning, allowing MATLAB to continue executing subsequent commands. If the caught exception has a
different error identifier, MATLAB rethrows the exception.
Extended Capabilities
Thread-Based Environment
Run code in the background using MATLAB® backgroundPool
or accelerate code with Parallel Computing Toolbox™ ThreadPool
.
This function fully supports thread-based environments. For more information, see Run MATLAB Functions in Thread-Based Environment.
Version History
Introduced in R2007b
MATLAB Command
You clicked a link that corresponds to this MATLAB command:
Run the command by entering it in the MATLAB Command Window. Web browsers do not support MATLAB commands.
Select a Web Site
Choose a web site to get translated content where available and see local events and offers. Based on your location, we recommend that you select: .
You can also select a web site from the following list
How to Get Best Site Performance
Select the China site (in Chinese or English) for best site performance. Other MathWorks country sites are not optimized for visits from your location.
Americas
- América Latina (Español)
- Canada (English)
- United States (English)
Europe
- Belgium (English)
- Denmark (English)
- Deutschland (Deutsch)
- España (Español)
- Finland (English)
- France (Français)
- Ireland (English)
- Italia (Italiano)
- Luxembourg (English)
- Netherlands (English)
- Norway (English)
- Österreich (Deutsch)
- Portugal (English)
- Sweden (English)
- Switzerland
- United Kingdom (English)
Asia Pacific
- Australia (English)
- India (English)
- New Zealand (English)
- 中国
- 日本Japanese (日本語)
- 한국Korean (한국어)