Main Content

addCause

记录异常的其他原因

说明

示例

baseException = addCause(baseException,causeException) 通过将 causeException 追加到它的 cause 属性修改现有 MException 对象的 baseException。在 try/catch 语句中捕获生成的异常可生成基础异常以及追加的所有原因记录,以帮助诊断错误。

示例

全部折叠

创建一个数组,并用逻辑数组创建对该数组的索引。

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

创建一个异常,提供有关错误的一般信息。测试索引数组并为异常添加有关失败来源的详细信息。

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.

检查 baseException 对象。

baseException
baseException = 

  MException with properties:

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

cause 属性的值是 2x1 元胞数组。

检查第一个异常原因。

baseException.cause{1}
ans = 

  MException with properties:

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

检查第二个异常原因。

baseException.cause{2}
ans = 

  MException with properties:

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

输入参数

全部折叠

包含错误的主要原因和位置的主异常,指定为 MException 对象。

包含与 baseException 相关的错误原因和位置的相关异常,指定为 MException 对象。

扩展功能

基于线程的环境
使用 MATLAB® backgroundPool 在后台运行代码或使用 Parallel Computing Toolbox™ ThreadPool 加快代码运行速度。

版本历史记录

在 R2007b 中推出