When the MATLAB® software throws an exception, it captures information about what
caused the error in a data structure called an MException
object.
This object is an instance of the MATLAB
MException
class. You can obtain access to the
MException
object by catching the
exception before your program aborts and accessing the object constructed for this
particular error via the catch
command. When throwing an
exception in response to an error in your own code, you will have to create a new
MException
object and store information about the error in
that object.
This section describes the MException
class and objects
constructed from that class:
Information on how to use this class is presented in later sections on Respond to an Exception and Throw an Exception.
The figure shown below illustrates one possible configuration of an object of the
MException
class. The object has four properties:
identifier
, message
,
stack
, and cause
. Each of these properties
is implemented as a field of the structure that represents the
MException
object. The stack
field is an
N-by-1 array of additional structures, each one identifying a function, and line
number from the call stack. The cause
field is an M-by-1 cell
array of MException
objects, each representing an exception that
is related to the current one.
See Properties of the MException Class for a full description of these properties.
Any code that detects an error and throws an exception must also construct an
MException
object in which to record and transfer
information about the error. The syntax of the MException
constructor is
ME = MException(identifier, message)
where identifier
is a MATLAB
message identifier
of the form
component:mnemonic
that is enclosed in single quotes, and message
is text,
also enclosed in single quotes, that describes the error. The output
ME
is the resulting MException
object.
If you are responding to an exception rather than throwing one, you do not
have to construct an MException
object. The object has
already been constructed and populated by the code that originally detected the
error.
The MException
class has four properties. Each of these
properties is implemented as a field of the structure that represents the
MException
object. Each of these properties is described in
the sections below and referenced in the sections on Respond to an Exception and Throw an Exception. All are read-only; their values cannot be
changed.
The MException
properties are:
If you call the surf
function with no inputs, MATLAB throws an exception. If you catch the exception, you can see the four
properties of the MException
object structure. (This example uses
try/catch
in an atypical fashion. See the section on The try/catch Statement for more information on using
try/catch
).
try surf catch ME ME end
Run this at the command line and MATLAB returns the contents of the MException
object:
ME = MException object with properties: identifier: 'MATLAB:narginchk:notEnoughInputs' message: 'Not enough input arguments.' stack: [1x1 struct] cause: {}
The stack
field shows the filename, function, and line number
where the exception was thrown:
ME.stack
ans =
file: 'matlabroot\toolbox\matlab\graph3d\surf.m'
name: 'surf'
line: 54
The cause
field is empty in this case. Each field is described
in more detail in the sections that follow.
A message identifier is a tag that you attach to an error or warning statement that makes that error or warning uniquely recognizable by MATLAB. You can use message identifiers with error reporting to better identify the source of an error, or with warnings to control any selected subset of the warnings in your programs.
The message identifier is a read-only character vector that specifies a component and a mnemonic label for an error or warning. The format of a simple identifier is
component:mnemonic
A colon separates the two parts of the identifier:
component
and mnemonic
. If the
identifier uses more than one component
, then additional
colons are required to separate them. A message identifier must always contain
at least one colon.
Some examples of message identifiers are
MATLAB:rmpath:DirNotFound MATLAB:odearguments:InconsistentDataType Simulink:actionNotTaken TechCorp:OpenFile:notFoundInPath
Both the component
and mnemonic
fields
must adhere to the following syntax rules:
No white space (space or tab characters) is allowed anywhere in the identifier.
The first character must be alphabetic, either uppercase or lowercase.
The remaining characters can be alphanumeric or an underscore.
There is no length limitation to either the component
or
mnemonic
. The identifier can also be an empty character
vector.
Component Field. The component
field specifies a broad category under
which various errors and warnings can be generated. Common components are a
particular product or toolbox name, such as MATLAB
or
Control
, or perhaps the name of your company, such as
TechCorp
in the preceding example.
You can also use this field to specify a multilevel component. The following statement has a three-level component followed by a mnemonic label:
TechCorp:TestEquipDiv:Waveform:obsoleteSyntax
The component field enables you to guarantee the uniqueness of each
identifier. Thus, while the internal MATLAB code might use a certain warning identifier like
MATLAB:InconsistentDataType
, that does not preclude
you from using the same mnemonic, as long as you precede it with a unique
component. For example,
warning('TechCorp:InconsistentDataType', ... 'Value %s is inconsistent with existing properties.' ... sprocketDiam)
Mnemonic Field. The mnemonic
field is normally used as a tag relating
to the particular message. For example, when reporting an error resulting
from the use of ambiguous syntax, a simple component and mnemonic such as
the following might be appropriate:
MATLAB:ambiguousSyntax
Message Identifiers in an MException Object. When throwing an exception, create an appropriate identifier and save it
to the MException
object at the time you construct the
object using the syntax
ME = MException(identifier, text)
For example,
ME = MException('AcctError:NoClient', ... 'Client name not recognized.'); ME.identifier ans = AcctError:NoClient
When responding to an exception, you can extract the message identifier
from the MException
object as shown here. Using the
surf
example again,
try surf catch ME id = ME.identifier end id = MATLAB:narginchk:notEnoughInputs
An error message in MATLAB is a read-only character vector issued by the program code and
returned in the MException
object. This message can assist
the user in determining the cause, and possibly the remedy, of the
failure.
When throwing an exception, compose an appropriate error message and save it
to the MException
object at the time you construct the object
using the syntax
ME = MException(identifier, text)
If your message requires formatting specifications, like those available with
the sprintf
function, use this syntax for the
MException
constructor:
ME = MException(identifier, formatstring, arg1, arg2, ...)
For example,
S = 'Accounts'; f1 = 'ClientName'; ME = MException('AcctError:Incomplete', ... 'Field ''%s.%s'' is not defined.', S, f1); ME.message ans = Field 'Accounts.ClientName' is not defined.
When responding to an exception, you can extract the error message from the
MException
object as follows:
try surf catch ME msg = ME.message end msg = Not enough input arguments.
The stack
field of the MException
object
identifies the line number, function, and filename where the error was detected.
If the error occurs in a called function, as in the following example, the
stack
field contains the line number, function name, and
filename not only for the location of the immediate error, but also for each of
the calling functions. In this case, stack
is an N-by-1
array, where N represents the depth of the call stack. That is, the stack field
displays the function name and line number where the exception occurred, the
name and line number of the caller, the caller's caller, etc., until the
top-most function is reached.
When throwing an exception, MATLAB stores call stack information in the stack
field. You cannot write to this field; access is read-only.
For example, suppose you have three functions that reside in two separate files:
mfileA.m ========================= . . 42 function A1(x, y) 43 B1(x, y); mfileB.m ========================= . . 8 function B1(x, y) 9 B2(x, y) . . 26 function B2(x, y) 27 . 28 . 29 . 30 . 31 % Throw exception here
Catch the exception in variable ME
and then examine the
stack
field:
for k=1:length(ME.stack) ME.stack(k) end ans = file: 'C:\matlab\test\mfileB.m' name: 'B2' line: 31 ans = file: 'C:\matlab\test\mfileB.m' name: 'B1' line: 9 ans = file: 'C:\matlab\test\mfileA.m' name: 'A1' line: 43
In some situations, it can be important to record information about not only
the one command that caused execution to stop, but also other exceptions that
your code caught. You can save these additional MException
objects in the cause
field of the primary exception.
The cause
field of an MException
is an
optional cell array of related MException
objects. You must
use the following syntax when adding objects to the cause
cell array:
primaryException = addCause(primaryException, secondaryException)
This example attempts to assign an array D
to variable
X
. If the D
array does not exist, the
code attempts to load it from a MAT-file and then retries assigning it to
X
. If the load fails, a new MException
object (ME3
) is constructed to store the cause of the first
two errors (ME1
and ME2
):
try X = D(1:25) catch ME1 try filename = 'test200'; load(filename); X = D(1:25) catch ME2 ME3 = MException('MATLAB:LoadErr', ... 'Unable to load from file %s', filename); ME3 = addCause(ME3, ME1); ME3 = addCause(ME3, ME2); end end
There are two exceptions in the cause field of ME3
:
ME3.cause ans = [1x1 MException] [1x1 MException]
Examine the cause
field of ME3
to see
the related errors:
ME3.cause{:} ans = MException object with properties: identifier: 'MATLAB:UndefinedFunction' message: 'Undefined function or method 'D' for input arguments of type 'double'.' stack: [0x1 struct] cause: {} ans = MException object with properties: identifier: 'MATLAB:load:couldNotReadFile' message: 'Unable to read file test204: No such file or directory.' stack: [0x1 struct] cause: {}
There are ten methods that you can use with the MException
class. The names of these methods are case-sensitive. See the MATLAB function reference pages for more information.
Method Name | Description |
---|---|
MException.addCause | Append an MException to the
cause field of another
MException . |
MException.getReport | Return a formatted message based on the current exception. |
MException.last | Return the last uncaught exception. This is a static method. |
MException.rethrow | Reissue an exception that has previously been caught. |
MException.throw | Issue an exception. |
MException.throwAsCaller | Issue an exception, but omit the current stack frame from the
stack field. |