Main Content

addCause

Record additional causes of exception

Description

example

baseException = addCause(baseException,causeException) modifies the existing MException object baseException by appending causeException to its cause property. Catching the resulting exception in a try/catch statement makes the base exception, along with all of the appended cause records, available to help diagnose the error.

Examples

collapse all

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.

try
    A(idx);
catch
    errID = 'MYFUN:BadIndex';
    msg = 'Unable to index into array.';
    baseException = MException(errID,msg);
    
    try
        assert(islogical(idx),'MYFUN:notLogical',...
            'Indexing array is not logical.')
    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
    throw(baseException)
end
Unable to index into array.

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

Examine the baseException object.

baseException
baseException = 

  MException with properties:

    identifier: 'MYFUN:BadIndex'
       message: 'Unable to index into array.'
         cause: {2x1 cell}
         stack: [0x1 struct]

The value of the cause property is a 2x1 cell array.

Examine the first cause of the exception.

baseException.cause{1}
ans = 

  MException with properties:

    identifier: 'MYFUN:notLogical'
       message: 'Indexing array is not logical.'
         cause: {0x1 cell}
         stack: [0x1 struct]

Examine the second cause of the exception.

baseException.cause{2}
ans = 

  MException with properties:

    identifier: 'MYFUN:incorrectSize'
       message: 'Indexing array is too large.'
         cause: {}
         stack: [0x1 struct]

Input Arguments

collapse all

Primary exception containing the primary cause and location of an error, specified as an MException object.

Related exception containing the cause and location of an error related to baseException, specified as an MException object.

Extended Capabilities

Thread-Based Environment
Run code in the background using MATLAB® backgroundPool or accelerate code with Parallel Computing Toolbox™ ThreadPool.

Version History

Introduced in R2007b