Documentation

This is machine translation

Translated by Microsoft
Mouseover text to see original. Click the button below to return to the English verison of the page.

Note: This page has been translated by MathWorks. Please click here
To view all translated materals including this page, select Japan from the country navigator on the bottom of this page.

addCause

Class: MException

Record additional causes of exception

Syntax

baseException = addCause(baseException,causeException)

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.

Input Arguments

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

Examples

expand 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
    msgID = 'MYFUN:BadIndex';
    msg = 'Unable to index into array.';
    baseException = MException(msgID,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))
        msgID = 'MYFUN:incorrectSize';
        msg = 'Indexing array is too large.';
        causeException2 = MException(msgID,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]

Introduced in R2007b

Was this topic helpful?