MATLAB 中 MException 类的方法

MException 类的方法

有几种方法可以与 MException 类一起使用。 这些方法的名称区分大小写。

MException.addCause将 MException 附加到另一个 MException 的 cause 字段
MException.getReport根据当前异常返回格式化消息
MException.last返回最后一次未捕获的异常(静态方法)
MException.rethrow重新发出先前捕获的异常
MException.throw发出异常
MException.throwAsCaller发出异常,但忽略堆栈字段中的当前堆栈帧

 

addCause

记录添加的异常原因

语法

baseException = addCause(baseException,causeException)

baseException = addCause(baseException,causeException) 通过将 causeException 附加到 baseException 的 cause 属性来修改现有的 baseException 对象。 在 try/catch 语句中捕获结果异常以及所有附加的 cause 记录可用于帮助诊断错误。

输入参数

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

causeException:相关异常,MException 对象。相关异常包含关于 baseException 对象的错误的原因和位置。

示例

创建一个数组,并使用逻辑数组创建其索引。

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

生成一个提供错误一般信息的异常。测试索引数组并添加详细的错误信息。

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.

检查 baseException:

baseException

结果 :

baseException = 

  MException with properties:

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

检查异常的第一个 cause:

baseException.cause{1}
ans = 

  MException with properties:

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

检查异常的第二个 cause:

baseException.cause{2}

结果:

ans = 

  MException with properties:

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

getReport

获取异常的错误消息

语法

msgText = getReport(exception)
msgText = getReport(exception,type)
msgText = getReport(exception,type,'hyperlinks',hlink)

msgText = getReport(exception)获取异常的错误消息,并将其作为格式化文本 msgText 返回。 该消息是 MException 对象的message 属性的值。 它与抛出异常时 MATLAB 命令行 显示的文本相同。

msgText = getReport(exception,type)使用指定的详细级别返回错误消息,由 type 指定。

msgText = getReport(exception,type,'hyperlinks',hlink)使用 hlink 的值来确定是否在错误消息中包含错误代码行的超链接。

输入参数

exception:提供错误消息的异常对象,指定为标量 MException 对象。

type:返回消息的详细指示符,指定为“extended”或“basic”。

extended(默认)msgText 包括行号,错误消息,原因和堆栈摘要。 要显示正确的堆栈,MATLAB首先必须抛出异常。
basic

msgText 包含错误消息。

hlink:消息的超链接指示符,包括指向错误代码行的活动超链接,指定为“on”,“off”或“default”。

on显示失败的代码行的超链接
off不要显示失败的代码行的超链接
default使用命令窗口的默认值来确定是否在错误消息中使用超链接

示例1:从异常中获取错误消息

导致 MATLAB 抛出异常。

plus

结果

Error using +
Not enough input arguments.

从异常中获取错误消息。

exception = MException.last;
msgText = getReport(exception)

结果

msgText =

Error using +
Not enough input arguments.

示例二:在错误消息中指定详细级别

在当前工作文件夹的文件中,在 testFunc.m 中创建以下函数。

function a = testFunc
try
    a = notaFunction(5,6);
catch a

end

由于函数不符合函数条件,即函数不存在,因此 testFunc 返回一个 MException 对象。

在命令提示符下,调用 testFunc 并获取错误消息。

m = testFunc;
msgText = getReport(m)
msgText =

Undefined function 'notaFunction' for input arguments of type 'double'.

Error in testFunc (line 3)
    a = notaFunction(5,6);

指定错误消息仅包含错误消息,而不包含堆栈信息。

msgText = getReport(m,'basic')

结果

msgText =

Undefined function 'notaFunction' for input arguments of type 'double'.

示例三:关闭错误消息中的超链接

导致 MATLAB 抛出异常。

try 
    surf
catch exception
end

从异常中获取错误消息。

msgText = getReport(exception)

结果

msgText =

Error using surf (line 49)
Not enough input arguments.

关闭错误消息中的超链接。

msgText = getReport(exception,'extended','hyperlinks','off')

结果

msgText =

Error using surf (line 49)
Not enough input arguments.

last

返回最后未捕获的异常

语法

exception = MException.last
MException.last('reset')

exception = MException.last 返回最近抛出的未捕获的 MException 对象的内容。 如果 try/catch 语句捕获到最后一个异常,则不设置 MException.last。 MException.last 是 MException 类的静态方法。

MException.last('reset')清除从 MException.last 返回的异常的属性。 它将 MException identifier 和 message 属性设置为空字符向量,将 stack 属性设置为 0x1 结构,将 cause 属性设置为空胞元数组。

示例1:捕获最后未被捕获的异常

使 MATLAB 抛出异常,但不捕获:

A = 25;
A(2)

结果:

Index exceeds matrix dimensions.

捕获异常:

exception = MException.last

结果: 

exception = 

  MException with properties:

    identifier: 'MATLAB:badsubscript'
       message: 'Index exceeds matrix dimensions.'
         cause: {}
         stack: [0x1 struct]

示例2:重置上次未捕获的异常

无输入参数调用surf函数

surf

提示报错

Error using surf (line 49)
Not enough input arguments.

取得未捕获的异常

exception = MException.last

结果

exception = 

  MException with properties:

    identifier: 'MATLAB:narginchk:notEnoughInputs'
       message: 'Not enough input arguments.'
         cause: {}
         stack: [1x1 struct]

使用上次未捕获的异常

MException.last('reset')
exception = MException.last

结果

exception = 

  MException with properties:

    identifier: ''
       message: ''
         cause: {0x1 cell}
         stack: [0x1 struct]

注意:MExeption.last只能通过命令行调用,不能在函数中使用。

rethrow

重新抛出先前捕获的异常

语法

rethrow(exception)

 rethrow(exception) 重新抛出一个先前捕获的异常 exception。MATLAB通过终止当前运行程序来响应错误。但是你可以用过使用 use/catch 块来捕获异常。这会中断程序终端,所以你可以执行以及的错误处理过程。用 reghrow 语句来结束 catch 块以终止程序并重新显示异常。

rethrow 处理堆栈跟踪与 error,assert 和 throw 不同。rethrow 不是保留从 MATLAB 执行该方法的位置创建堆栈,而是保留原始异常信息并使您能够追溯原始错误的来源。

输入参数

exception:包含错误的 cause 和 location 信息,指定为标量 MException 对象。

示例1:捕获和重新抛出异常

调用无参数 surf 函数使 MATLAB抛出异常。捕获这个异常,显示错误定义,重新抛出异常。

try
    surf
catch ME
    disp(['ID: ' ME.identifier])
    rethrow(ME)
end

结果:

ID: MATLAB:narginchk:notEnoughInputs
Error using surf (line 49)
Not enough input arguments.

示例2:比较 throw 和 rethrow

在工作文件夹创建 combineArrays 函数

function C = combineArrays(A,B)
try
    C = catAlongDim1(A,B);       % Line 3
catch exception
    throw(exception)             % Line 5
end
end

function V = catAlongDim1(V1,V2)
V = cat(1,V1,V2);                % Line 10
end

用不同大小的数组调用 CombineArrays 函数。

A = 1:5;
B = 1:4;

combineArrays(A,B)

结果:

Error using combineArrays (line 5)
Dimensions of matrices being concatenated are not consistent.

堆栈指向引发异常的第5行。

在 combinedArrays 函数的第5行上,用 throw(exception) 替换 throw(exception),然后再次调用该函数。

combineArrays(A,B)

结果:

Error using cat
Dimensions of matrices being concatenated are not consistent.

Error in combineArrays>catAlongDim1 (line 10)
V = cat(1,V1,V2);                % Line 10

Error in combineArrays (line 3)
    C = catAlongDim1(A,B);       % Line 3

rethrow 方法包含原始堆栈,表明错误在第三行。

throw

抛出错误

语法

throw(exception)

throw(exception) 基于MException对象exception 抛出异常。异常终止当前运行函数,返回控制权到键盘或封闭的 catch 块。当你从一个外部 try/catch 语句抛出异常时,MATLAB 在命令行中显示错误信息。

throw 方法与 throwAsCaller 和 rethrow 方法不同,它在执行该方法的位置创建堆栈跟踪。

可以通过 try/catch 语句或者 MException.last方法访问 MException对象。

输入参数

exception:包含错误的 cause 和 location 信息,指定为标量 MException 对象。

示例1:创建和抛出 MException 对象

如果输入变量不存在于当前工作空间时将会引发异常。

str = input('Type a variable name: ','s');
if ~exist(str,'var')
    ME = MException('MyComponent:noSuchVariable', ...
        'Variable %s not found',str);
    throw(ME)
end

在输入提示下,输入工作空间中不存在的任何变量。 例如,输入 notaVariable。

Variable notaVariable not found

因为 notVariable 不存在于当前工作空间,MATLAB创建 MException 对象,抛出异常。

示例2:比较 throw 和 rethrow

在工作文件夹创建 combineArrays 函数

function C = combineArrays(A,B)
try
    C = catAlongDim1(A,B);       % Line 3
catch exception
    throw(exception)             % Line 5
end
end

function V = catAlongDim1(V1,V2)
V = cat(1,V1,V2);                % Line 10
end

用不同大小的数组调用 CombineArrays 函数。

A = 1:5;
B = 1:4;

combineArrays(A,B)

结果:

Error using combineArrays (line 5)
Dimensions of matrices being concatenated are not consistent.

堆栈指向引发异常的第5行。

在 combinedArrays 函数的第5行上,用 throw(exception) 替换 throw(exception),然后再次调用该函数。

combineArrays(A,B)

结果:

Error using cat
Dimensions of matrices being concatenated are not consistent.

Error in combineArrays>catAlongDim1 (line 10)
V = cat(1,V1,V2);                % Line 10

Error in combineArrays (line 3)
    C = catAlongDim1(A,B);       % Line 3

rethrow 方法包含原始堆栈,表明错误在第三行。

throwAsCaller

如同调用函数一样抛出异常

语法

throwAsCaller(exception)

throwAsCaller(exception) 抛出异常好像在调用函数中。异常终止当前运行函数,返回控制权到键盘或者封闭的 catch 块。当你从外部 try/catch 语句调用异常时,MATLAB 在命令行窗口中显示错误信息。

你可以通过 try/catch 语句或者 MException.last 方法访问 MException 对象。

某种情况下,错误指向导致异常的调用函数中的位置比指向实际引发异常的函数更具参考价值。 可以使用 throwAsCaller 简化错误显示。

输入参数

exception:包含错误的 cause 和 location 信息,指定为标量 MException 对象。

示例:比较 throw 和 throwAsCaller

在工作文件夹创建函数 sayHello

function sayHello(N)
checkInput(N)
str = ['Hello, ' N '!'];
disp(str)

function checkInput(N)
if ~ischar(N)
    ME = MException('sayHello:inputError','Input must be char.');
    throw(ME)
end

在命令提示下,用数值输入调用函数。

sayHello(42)

结果:

Error using sayHello>checkInput (line 9)
Input must be char.

Error in sayHello (line 2)
checkInput(N)

栈首指向抛出错误的第9行。在初始化堆栈之后,MATLAB 显示来自调用函数的信息。

用 throwAsCaller(ME) 替换 throw(ME),然后再次调用该函数。

sayHello(42)

结果:

Error using sayHello (line 2)
Input must be char.

堆栈首指向调用函数错误位置的第2行。

 

参考资料:

1.MATLAB 官方文档:https://ww2.mathworks.cn/help/ 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值