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.

Throw an Exception

When your program detects a fault that will keep it from completing as expected or will generate erroneous results, you should halt further execution and report the error by throwing an exception. The basic steps to take are

  1. Detect the error. This is often done with some type of conditional statement, such as an if or try/catch statement that checks the output of the current operation.

  2. Construct an MException object to represent the error. Add a message identifier and error message to the object when calling the constructor.

  3. If there are other exceptions that may have contributed to the current error, you can store the MException object for each in the cause field of a single MException that you intend to throw. Use the addCause method for this.

  4. Use the throw or throwAsCaller function to have the MATLAB® software issue the exception. At this point, MATLAB stores call stack information in the stack field of the MException, exits the currently running function, and returns control to either the keyboard or an enclosing catch block in a calling function.

This example illustrates throwing an exception using the steps just described:

Create an array, and an index into it with a logical array.

A = [13 42; 7 20];
idx = [1 0 1; 0 1 0];

Create an exception that provides general information about an error. Test the index array and add exceptions with more detailed information about the source of the failure.

% 1) Detect the error.
    % 2) Construct an MException object to represent the error.
    msgID = 'MYFUN:BadIndex';
    msg = 'Unable to index into array.';
    baseException = MException(msgID,msg);
    % 3) Store any information contributing to the error.
            'Indexing array is not logical.')
    catch causeException
        baseException = addCause(baseException,causeException);
    if any(size(idx) > size(A))
        msgID = 'MYFUN:incorrectSize';
        msg = 'Indexing array is too large.';
        causeException2 = MException(msgID,msg);
        baseException = addCause(baseException,causeException2);
    % 4) Throw the exception to stop execution and display an error
    % message.
Unable to index into array.

Caused by:
    Indexing array is not logical.
    Indexing array is too large.