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安装Pandas库的两种方法

《Python安装Pandas库的两种方法》本文介绍了三种安装PythonPandas库的方法,通过cmd命令行安装并解决版本冲突,手动下载whl文件安装,更换国内镜像源加速下载,最后建议用pipli... 目录方法一:cmd命令行执行pip install pandas方法二:找到pandas下载库,然后

Linux系统中查询JDK安装目录的几种常用方法

《Linux系统中查询JDK安装目录的几种常用方法》:本文主要介绍Linux系统中查询JDK安装目录的几种常用方法,方法分别是通过update-alternatives、Java命令、环境变量及目... 目录方法 1:通过update-alternatives查询(推荐)方法 2:检查所有已安装的 JDK方

SQL Server安装时候没有中文选项的解决方法

《SQLServer安装时候没有中文选项的解决方法》用户安装SQLServer时界面全英文,无中文选项,通过修改安装设置中的国家或地区为中文中国,重启安装程序后界面恢复中文,解决了问题,对SQLSe... 你是不是在安装SQL Server时候发现安装界面和别人不同,并且无论如何都没有中文选项?这个问题也

Java Thread中join方法使用举例详解

《JavaThread中join方法使用举例详解》JavaThread中join()方法主要是让调用改方法的thread完成run方法里面的东西后,在执行join()方法后面的代码,这篇文章主要介绍... 目录前言1.join()方法的定义和作用2.join()方法的三个重载版本3.join()方法的工作原

在MySQL中实现冷热数据分离的方法及使用场景底层原理解析

《在MySQL中实现冷热数据分离的方法及使用场景底层原理解析》MySQL冷热数据分离通过分表/分区策略、数据归档和索引优化,将频繁访问的热数据与冷数据分开存储,提升查询效率并降低存储成本,适用于高并发... 目录实现冷热数据分离1. 分表策略2. 使用分区表3. 数据归档与迁移在mysql中实现冷热数据分

Spring Boot从main方法到内嵌Tomcat的全过程(自动化流程)

《SpringBoot从main方法到内嵌Tomcat的全过程(自动化流程)》SpringBoot启动始于main方法,创建SpringApplication实例,初始化上下文,准备环境,刷新容器并... 目录1. 入口:main方法2. SpringApplication初始化2.1 构造阶段3. 运行阶

Olingo分析和实践之ODataImpl详细分析(重要方法详解)

《Olingo分析和实践之ODataImpl详细分析(重要方法详解)》ODataImpl.java是ApacheOlingoOData框架的核心工厂类,负责创建序列化器、反序列化器和处理器等组件,... 目录概述主要职责类结构与继承关系核心功能分析1. 序列化器管理2. 反序列化器管理3. 处理器管理重要方

Python错误AttributeError: 'NoneType' object has no attribute问题的彻底解决方法

《Python错误AttributeError:NoneTypeobjecthasnoattribute问题的彻底解决方法》在Python项目开发和调试过程中,经常会碰到这样一个异常信息... 目录问题背景与概述错误解读:AttributeError: 'NoneType' object has no at

postgresql使用UUID函数的方法

《postgresql使用UUID函数的方法》本文给大家介绍postgresql使用UUID函数的方法,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友参考下吧... 目录PostgreSQL有两种生成uuid的方法。可以先通过sql查看是否已安装扩展函数,和可以安装的扩展函数

Java中Arrays类和Collections类常用方法示例详解

《Java中Arrays类和Collections类常用方法示例详解》本文总结了Java中Arrays和Collections类的常用方法,涵盖数组填充、排序、搜索、复制、列表转换等操作,帮助开发者高... 目录Arrays.fill()相关用法Arrays.toString()Arrays.sort()A