14

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

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.

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?

(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!)

4

2 回答 2

7

这两种情况实际上是等效的(如果您发现错误或异常,唯一的区别是'cause'属性单元的分配略有不同)。该error函数只是使生成和抛出异常变得容易。一件好事MException是您可以创建一个 MException 对象并将其作为变量传递,更改其属性(例如,添加 cause),throwrethrow在需要时。但是,大多数时候您只想使用error

MathWorks 的此页面包含有关 MException 类的大量详细信息。

于 2013-07-26T17:26:19.683 回答
2

MATLAB Answers上有关于这个线程的一些更有用的信息。

答案说错误更老,而 MException 更新更灵活。已修改错误以创建 MException。

Error 被认为更易于使用,并针对来自科学和工程社区的 MATLAB 最终用户。MException 更高级(因为可以修改和重新抛出 ME 对象)并且针对软件开发社区。

于 2016-09-26T11:32:50.313 回答