MException class

Capture error information


Any MATLAB® code that detects an error and throws an exception must construct an MException object. This class contains retrievable information about errors. MATLAB can throw either predefined exceptions or exceptions that you construct.


ME = MException(msgID,msgtext) captures information about a specific error and stores it in the MException object, ME. The MException object is constructed with a message identifier, msgID, and an error message string, msgtext.

ME = MException(msgID,msgtext,A1,...,An) allows formatting of the error message string using text or numeric values, A1,...,An, to replace conversion specifiers in msgtext at run time.

Input Arguments

collapse all

msgID — Identifier for errorstring

Identifier for the error, specified as a string. Use the message 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 message identifier includes a component and mneumonic. The identifier must always contain a colon and follows a simple format: component:mnemonic. The component and mneumonic 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 anywhere in msgID. For more information, see Message Identifiers.

Example: 'MyComponent:noSuchVariable'

msgtext — Information about cause of errorstring

Information about the cause of the error and how you might correct it, specified as a string. To format the string, 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 via the A1,...,An input arguments. For more information, see Formatting Strings.

Example: 'Error opening file.'

Example: 'Error on line %d.'

A1,...,An — Numeric or character arraysscalar | vector | matrix | multidimensional array

Numeric or character arrays, specified as a scalar, vector, matrix, or multidimensional array. This input argument provides the values that correspond to and replace the conversion specifiers in msgtext.


collapse all

identifierUnique identifier of errorstring

String that uniquely identifies the error, specified as a string by the msgID input argument. This property is read only. For more information, see Message Identifiers.

messageError messagestring

String that contains the error message that is displayed when MATLAB throws the exception, specified by the msgtext and A1,...,An input arguments. This property is read only. For more information, see Text of the Error Message.

stackStack trace informationarray of structures

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. This property is read only. For more information, see The Call Stack.

causeCause of the exceptioncell array of MException objects

Cell array of MException objects that caused MATLAB to create this exception. Use the addCause method to add an exception to the cause field of the another exception. For more information, see The Cause Array.


addCauseRecord additional causes of exception
getReportGet error message for exception
lastReturn last uncaught exception
rethrowRethrow previously caught exception
throwThrow exception
throwAsCallerThrow exception as if occurs within calling function

Copy Semantics

Value. To learn how value classes affect copy operations, see Copying Objects in the MATLAB documentation.


collapse all

Create MException Object

msgID = 'myComponent:inputError';
msgtext = 'Input does not have the expected format.';

ME = MException(msgID,msgtext)
ME = 

  MException with properties:

    identifier: 'myComponent:inputError'
       message: 'Input does not have the expected format.'
         cause: {}
         stack: [0x1 struct]

Create MException with Formatted Error Message

msgID = 'MATLAB:test';
msgtext = 'There are %d errors on this page';
A1 = 10;

ME = MException(msgID,msgtext,A1)
ME = 

  MException with properties:

    identifier: 'MATLAB:test'
       message: 'There are 10 errors on this page'
         cause: {}
         stack: [0x1 struct]

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

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 an MException object, and then throws it.

Use try/catch to Capture 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.

    a = notaFunction(5,6);
catch ME
    if strcmp(ME.identifier,'MATLAB:UndefinedFunction')
        warning('Function is undefined.  Assigning a value of 0.');
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.

Related Examples

Was this topic helpful?