MATLAB 中 MException 类的方法

2023-10-27 14:18
文章标签 matlab 方法 mexception

本文主要是介绍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];

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

tryA(idx);
catchmsgID = 'MYFUN:BadIndex';msg = 'Unable to index into array.';baseException = MException(msgID,msg);tryassert(islogical(idx),'MYFUN:notLogical',...'Indexing array is not logical.')catch causeExceptionbaseException = addCause(baseException,causeException);endif any(size(idx) > size(A))msgID = 'MYFUN:incorrectSize';msg = 'Indexing array is too large.';causeException2 = MException(msgID,msg);baseException = addCause(baseException,causeException2);endthrow(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
trya = notaFunction(5,6);
catch aend

由于函数不符合函数条件,即函数不存在,因此 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抛出异常。捕获这个异常,显示错误定义,重新抛出异常。

trysurf
catch MEdisp(['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)
tryC = catAlongDim1(A,B);       % Line 3
catch exceptionthrow(exception)             % Line 5
end
endfunction 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 10Error 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)
tryC = catAlongDim1(A,B);       % Line 3
catch exceptionthrow(exception)             % Line 5
end
endfunction 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 10Error 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/ 

这篇关于MATLAB 中 MException 类的方法的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/286203

相关文章

Python常用命令提示符使用方法详解

《Python常用命令提示符使用方法详解》在学习python的过程中,我们需要用到命令提示符(CMD)进行环境的配置,:本文主要介绍Python常用命令提示符使用方法的相关资料,文中通过代码介绍的... 目录一、python环境基础命令【Windows】1、检查Python是否安装2、 查看Python的安

Maven 配置中的 <mirror>绕过 HTTP 阻断机制的方法

《Maven配置中的<mirror>绕过HTTP阻断机制的方法》:本文主要介绍Maven配置中的<mirror>绕过HTTP阻断机制的方法,本文给大家分享问题原因及解决方案,感兴趣的朋友一... 目录一、问题场景:升级 Maven 后构建失败二、解决方案:通过 <mirror> 配置覆盖默认行为1. 配置示

SpringBoot排查和解决JSON解析错误(400 Bad Request)的方法

《SpringBoot排查和解决JSON解析错误(400BadRequest)的方法》在开发SpringBootRESTfulAPI时,客户端与服务端的数据交互通常使用JSON格式,然而,JSON... 目录问题背景1. 问题描述2. 错误分析解决方案1. 手动重新输入jsON2. 使用工具清理JSON3.

使用jenv工具管理多个JDK版本的方法步骤

《使用jenv工具管理多个JDK版本的方法步骤》jenv是一个开源的Java环境管理工具,旨在帮助开发者在同一台机器上轻松管理和切换多个Java版本,:本文主要介绍使用jenv工具管理多个JD... 目录一、jenv到底是干啥的?二、jenv的核心功能(一)管理多个Java版本(二)支持插件扩展(三)环境隔

Java中Map.Entry()含义及方法使用代码

《Java中Map.Entry()含义及方法使用代码》:本文主要介绍Java中Map.Entry()含义及方法使用的相关资料,Map.Entry是Java中Map的静态内部接口,用于表示键值对,其... 目录前言 Map.Entry作用核心方法常见使用场景1. 遍历 Map 的所有键值对2. 直接修改 Ma

Mybatis Plus Join使用方法示例详解

《MybatisPlusJoin使用方法示例详解》:本文主要介绍MybatisPlusJoin使用方法示例详解,本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,... 目录1、pom文件2、yaml配置文件3、分页插件4、示例代码:5、测试代码6、和PageHelper结合6

Java中实现线程的创建和启动的方法

《Java中实现线程的创建和启动的方法》在Java中,实现线程的创建和启动是两个不同但紧密相关的概念,理解为什么要启动线程(调用start()方法)而非直接调用run()方法,是掌握多线程编程的关键,... 目录1. 线程的生命周期2. start() vs run() 的本质区别3. 为什么必须通过 st

C#之List集合去重复对象的实现方法

《C#之List集合去重复对象的实现方法》:本文主要介绍C#之List集合去重复对象的实现方法,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录C# List集合去重复对象方法1、测试数据2、测试数据3、知识点补充总结C# List集合去重复对象方法1、测试数据

SpringBoot读取ZooKeeper(ZK)属性的方法实现

《SpringBoot读取ZooKeeper(ZK)属性的方法实现》本文主要介绍了SpringBoot读取ZooKeeper(ZK)属性的方法实现,强调使用@ConfigurationProperti... 目录1. 在配置文件中定义 ZK 属性application.propertiesapplicati

MyBatis设计SQL返回布尔值(Boolean)的常见方法

《MyBatis设计SQL返回布尔值(Boolean)的常见方法》这篇文章主要为大家详细介绍了MyBatis设计SQL返回布尔值(Boolean)的几种常见方法,文中的示例代码讲解详细,感兴趣的小伙伴... 目录方案一:使用COUNT查询存在性(推荐)方案二:条件表达式直接返回布尔方案三:存在性检查(EXI