Main Content

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

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

example

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

example

Input Arguments

expand all

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 field MATLAB, which means that the exception is thrown in MATLAB. You can reuse the same mnemonic TooManyInputs 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'

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

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

expand all

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'

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'

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.

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.

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

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

Examples

collapse all

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: []

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: []

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.

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.

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

Version History

Introduced in R2007b