Main Content

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 an error 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 function for this.

  4. If there is fix that can be suggested for the current error, you can add it to the Correction field of the MException that you intend to throw. Use the addCorrection function for this.

  5. Use the throw or throwAsCaller function to have MATLAB® 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.

Suggestions on How to Throw an Exception

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

Create a function, indexIntoArray, that indexes into a specified array using a specified index. The function catches any errors that MATLAB throws and creates an exception that provides general information about the error. When it catches an error, it detects whether the error involves the number of inputs or the specified index. If it does, the function adds additional exceptions with more detailed information about the source of the failure, and suggests corrections when possible.

function indexIntoArray(A,idx)

% 1) Detect the error.
try
    A(idx)
catch
    
    % 2) Construct an MException object to represent the error.
    errID = 'MYFUN:BadIndex';
    msg = 'Unable to index into array.';
    baseException = MException(errID,msg);
    
    % 3) Store any information contributing to the error. 
    if nargin < 2 
        causeException = MException('MATLAB:notEnoughInputs','Not enough input arguments.');
        baseException = addCause(baseException,causeException);
        
        % 4) Suggest a correction, if possible.
        if(nargin > 1) 
            exceptionCorrection = matlab.lang.correction.AppendArgumentsCorrection('1');
            baseException = baseException.addCorrection(exceptionCorrection);
        end
        
        throw(baseException);
    end
        
    try
        assert(isnumeric(idx),'MYFUN:notNumeric', ...
            'Indexing array is not numeric.')
    catch causeException
        baseException = addCause(baseException,causeException);
    end
    
    if any(size(idx) > size(A))
        errID = 'MYFUN:incorrectSize';
        msg = 'Indexing array is too large.';
        causeException2 = MException(errID,msg);
        baseException = addCause(baseException,causeException2);
    end
    
    % 5) Throw the exception to stop execution and display an error
    % message.
    throw(baseException)
end
end

If you call the function without specifying an index, the function throws a detailed error and suggests a correction:

A = [13 42; 7 20];
indexIntoArray(A)
Error using indexIntoArray
Unable to index into array.

Caused by:
    Not enough input arguments.
 
Did you mean:
>> indexIntoArray(A, 1)

If you call the function with a nonnumeric index array that is too large, the function throws a detailed error.

A = [13 42; 7 20];
idx = ['a' 'b' 'c'];
indexIntoArray(A, idx)
Error using indexIntoArray
Unable to index into array.

Caused by:
    Error using assert
    Indexing array is not numeric.
    Indexing array is too large.