Exceptions vs. Errors in Matlab

跟風遠走 提交于 2019-12-21 03:38:07

问题


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


回答1:


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.

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




回答2:


There is some more useful information on this thread on MATLAB Answers.

The answer says that error is much older and that MException is newer and more flexible. Error has been modified to create an MException.

Error is considered easier to use and targetted at MATLAB end users from the Scientific and Engineering community. MException is more advanced (in that ME objects can be modified and rethrown) and is targeted at the software development community.



来源:https://stackoverflow.com/questions/17886796/exceptions-vs-errors-in-matlab

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!