This is machine translation

Translated by Microsoft
Mouseover text to see original. Click the button below to return to the English version of the page.

Note: This page has been translated by MathWorks. Click here to see
To view all translated materials including this page, select Country from the country navigator on the bottom of this page.

Capture Information About Exceptions


When MATLAB® throws an exception, it captures information about the cause in a data structure called an MException object. This object is an instance of the MATLAB MException class. You can access 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 MException Class

The figure shown below illustrates one possible configuration of an object of the MException class. The object has five properties: identifier, message, stack, cause, and Correction. 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.

Object Constructor

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


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.

Properties of the MException Class

The MException class has several 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 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).

catch ME

Run this at the command line and MATLAB returns the contents of the MException object:

ME = 

  MException with properties:

    identifier: 'MATLAB:narginchk:notEnoughInputs'
       message: 'Not enough input arguments.'
         cause: {}
         stack: [1×1 struct]
    Correction: []

The stack field shows the filename, function, and line number where the exception was thrown:

ans = 
    file: 'matlabroot\toolbox\matlab\graph3d\surf.m'
    name: 'surf'
    line: 54

The cause and Correction fields are empty in this case. Each field is described in more detail in the sections that follow.

Message Identifiers

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


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


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:


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.' ...

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:


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.');

ans =

When responding to an exception, you can extract the message identifier from the MException object as shown here. Using the surf example again,

catch ME
    id = ME.identifier

id =

Text of the Error Message

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);

ans =
    Field 'Accounts.ClientName' is not defined.

When responding to an exception, you can extract the error message from the MException object as follows:

catch ME
    msg = ME.message

msg =
    Not enough input arguments.

The Call Stack

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:

42 function A1(x, y)
43 B1(x, y);

 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)

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

The Cause Array

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):

    X = D(1:25)
catch ME1
        filename = 'test200';
        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);

There are two exceptions in the cause field of ME3:

ans = 
    [1x1 MException]
    [1x1 MException]

Examine the cause field of ME3 to see the related errors:

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 
         stack: [0x1 struct]
         cause: {}

The Correction

Some exceptions may have a fix that can be suggested when the exception occurs. If you are throwing an exception, you can suggest a fix by creating a matlab.lang.correction.AppendArgumentsCorrection object and adding it to the Correction field of the exception.

You must use the following syntax when adding a fix to the Correction field:

primaryException = addCorrection(baseException,exceptionCorrection)

This example creates a function hello that requires one input argument. If the function is called without inputs, MATLAB produces and error and suggests the input argument "world" as a fix.

function hello(audience)
if nargin < 1
    me = MException('MATLAB:notEnoughInputs','Not enough input arguments.');
    aac = matlab.lang.correction.AppendArgumentsCorrection('"world"');
    me = me.addCorrection(aac);
fprintf("Hello, %s!\n", audience);

When you call the function without an argument, MATLAB suggests a fix.

Error using hello (line 6)
Not enough input arguments.

Did you mean:
>> hello("world")

Methods of the MException Class

There are several 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 NameDescription
addCauseAppend an MException to the cause field of another MException.
addCorrectionProvide a suggested fix for the current exception.
getReportReturn a formatted message based on the current exception.
MException.lastReturn the last uncaught exception. This is a static function.
rethrowReissue an exception that has previously been caught.
throwIssue an exception.
throwAsCallerIssue an exception, but omit the current stack frame from the stack field.