Matlab中的异常与错误 [英] Exceptions vs. Errors in Matlab

查看:164
本文介绍了Matlab中的异常与错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Matlab提供了两种机制,用于发信号通知发生错误:错误函数和语言的异常处理机制 MException + 尝试 / catch / throw

Matlab provides two mechanisms for signaling that something has gone wrong: the errorfunction and the language's exception-handling mechanisms MException + try/catch/throw.

看起来它们在很大程度上是等价的:错误函数和 MException 函数语法非常相似。通过 error()引发的错误可以被 catch 捕获,而与错误相关的工具(如 dbstop if error lasterr )似乎也适用于例外。

It looks like they are largely equivalent: The error function and the MException function have very similar syntax. Errors raised via error() can be caught by a catch, while the error-related tools (like dbstop if error and lasterr) seem to work with exceptions too.

有没有理由喜欢错误('Foo:Bar','关于bar的一些人类可读的消息') to throw(MException('Foo:Bar','Some humanable message'))反之亦然

Is there ever a reason to prefer error('Foo:Bar', 'Some human-readable message about bar') to throw(MException('Foo:Bar', 'Some human-readable message')) or vice versa?

(它们都是内置的,所以你不能打开(例如)error.m来查看是否有一个是一个平凡的包装器在另一个!)

(They're both built-ins, so you cannot just open (e.g.) error.m to see if one is a trivial wrapper around the other!)

推荐答案

这两种情况几乎相当(如果您遇到错误或异常,唯一的区别是导致'属性的单元格稍有不同)。 错误 函数只是使得生成和抛出异常变得容易。关于 MException 的一件好事是您可以创建一个MException对象并将其作为变量传递,更改其属性(例如,添加原因)和 throw rethrow 需要的时候。大部分时间您只想使用错误

Those two cases are virtually equivalent (if you catch an error or exception the only difference is that the 'cause' property's cell is allocated slightly differently). The error function just makes it easy to generate and throw exceptions. The one nice thing about MException is that you can create an MException object and pass it around as a variable, change its properties (e.g., adding a cause), and throw or rethrow when needed. Most of the time you'll just want to use error however.

此页面包含许多有关MException类的详细信息。

This page from the MathWorks includes lots of details on the MException class.

这篇关于Matlab中的异常与错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆