Main Content

引发异常

当您的程序检测到将阻止程序如期完成或将生成错误结果的故障时,您应该通过引发异常停止进一步执行并报告错误。采取的基本步骤是:

  1. 检测错误。这通常是使用某种类型的条件语句(如用于检查当前操作的输出的 iftry/catch 语句)完成的。

  2. 构造一个 MException 对象来表示该错误。在调用构造函数时向对象中添加一个错误标识符和一个错误消息。

  3. 如果有其他可能导致当前错误的异常,您可以将每个异常的 MException 对象存储在一个您打算引发的单个 MExceptioncause 字段中。要执行此操作,请使用 addCause 函数。

  4. 如果有针对当前错误的修复建议,您可以将其添加到要引发的 MExceptionCorrection 字段。要执行此操作,请使用 addCorrection 函数。

  5. 使用 throwthrowAsCaller 函数使 MATLAB® 引发异常。此时,MATLAB 将调用堆栈信息存储在 MExceptionstack 字段中,退出当前正在运行的函数,并将控制权交回给键盘或正在调用的函数中的封闭 catch 块。

关于如何引发异常的建议

以下示例展示了如何使用刚才所述的步骤引发异常。

创建一个函数 indexIntoArray,它使用指定的索引对指定的数组进行索引。该函数会捕获 MATLAB 引发的任何错误,并创建一个异常以提供有关错误的一般信息。当该函数捕获到错误时,它会检测该错误是否涉及输入数量或指定的索引。如果是,该函数会添加额外的异常以提供关于故障来源的更多详细信息,并尽可能提供更正建议。

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

如果您在未指定索引的情况下调用该函数,该函数会抛出详细的错误消息并提供更正建议:

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)

如果使用过大的非数值索引数组调用该函数,该函数会引发详细的错误。

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.