MATLAB Answers

Babak
5

There seems to be two different methods of error handling in MATLAB: "error handling" and "exception handling". What is the difference and which one is better?

Asked by Babak
on 14 Feb 2014
Latest activity Edited by Babak
on 3 Aug 2017
A good introduction to this question can be made by taking a look at the Java programming language: There is one best way of handling an unexpected situation, and that is simply to throw any Throwable object (that is, Exception or Error or any derived class thereof). The difference in Java between Exception and Error is that one should use Error in the case that recovering from it and continuing the application is not possible. For example, running out of memory would be an Error whereas encountering a String with an unexpected value would be an Exception. This is straightforward and only needs to be learned once.
In MATLAB, there are two distinct methods of handling errors, both of which can be handled by enclosing them in a try/catch statement:
  • Call the error() function, or a related/wrapper function, such as assert()
  • Create an MException object and throw it, for example throw(myExceptionObject)
This sounds okay so far because maybe there are situations where one is better or more efficient than the other. There must be some good reason why there are two. However, the confusion begins after some thought about why there would even exist more than one way of handling errors - why is there not just one, good method to handle errors? The confusion worsens when we start to look at the similarities and differences between the two different approaches provided in MATLAB. It seems that a line is drawn between the two approaches, while at the same time that line is blended into some sort of grey area.
Both the error() function and the constructor for the MException object accept a 'message identifier' and a 'message string'. In both cases the latter can optionally be a formatted string. The various ways of invoking these two methods are summarized below along with the URL of the source of the information.
  • error('msgIdent', 'msgString', v1, v2, ..., vN)
  • error('msgString', v1, v2, ...)
  • error('msgString')
  • error(msgStruct)
  • exception = MException(msgIdent, msgString, v1, v2, ..., vN)
By comparing the argument lists of the two different methods (shown above), it can be seen that they are nearly identical, although the error() function is overloaded and the MException constructor is not. If the syntax is almost identical, why are there two different things then? Couldn't there just be one?
Also, the description of the MException object states that it is meant to "[c]apture error information", as opposed to capturing exception information, suggesting that the two approaches are one and the same.
Another observation that blends the line between the two approaches can be seen in the URL in the Documentation Center for the article titled "Capture Information About Exceptions", which actually ends with "capture-information-about-errors.html", again suggesting that "exceptions" and "errors" are the same thing.
Yet another similarity, which was mentioned earlier as well, is the fact that both approaches are handled in the same way: enclosing them in a try/catch block in order to "catch" the error/exception. As a matter of fact, the error() function creates an MException object automatically, so in both cases an MException object is what's being handled in the catch clause. Again this begs the question: why are there two different ways?
Despite the striking similarities in functionality and syntax, these are still two different approaches for handling errors in MATLAB. This is evidenced by the two completely different Documentation Center articles on "Error Handling" (using error() ) versus "Exception Handling" (using throw(MException)| ):
This suggests that error() and throw(MException) are mutually exclusive techniques for handling errors, fully contradicting all the similarities pointed out above.
After analyzing the difference between the two methods forensically, it seems there may be a difference in the structure of the MException object that is created via the error() function versus that created via the MException() constructor. A user on a StackOverflow message board did a comparison between the MException objects created by error() and MException() and noted that "the 'cause' property's cell is allocated slightly differently".
Allaround, this is very confusing. It appears as though MATLAB treats "errors" and "exceptions" as two wholly different topics while at the same time intermingling various aspects of each other. My best theory right now is that error() is some sort of shortcut that does indeed throw(MException) somewhere inside, and that the MathWorks Documentation Center is a little disorganized/vague and should be updated. Is error() simply a shortcut/wrapper function that does throw(MException) inside? Why does the documentation suggest otherwise? And why would there need to be a shortcut/wrapper function if the syntax is nearly identical to the method it is "shortcutting"?
I would like to know more about MATLAB's code structure so I can more appropriately decide which one to use in a given situation. Unfortunately, both error() and throw(MException) are built-in functions so the source is not viewable and I cannot distinguish between the two. I suppose the root of all this is that I don't understand why there would even need to be more than one way of handling errors, especially since the two methods provided in MATLAB are nearly identical in syntax.

  0 Comments

Sign in to comment.

2 Answers

Answer by Leo Ng
on 15 Feb 2014
Edited by Leo Ng
on 15 Feb 2014
 Accepted Answer

Hello Babak,
The "error" function has been a part of MATLAB for a very long time---much longer than "MException" objects have been a part of MATLAB. The "error" function provides a simple syntax to handle the most basic and common case: you want to display an error message and cause your program to stop running. But sometimes you want to do something more advanced like catch an error that some other code threw, modify the message or other information about the error, and cause it to be thrown again. The "MException" object allows you to perform those more advanced tasks, and when it was introduced to handle those more advanced tasks, "error" was modified to essentially create and throw an "MException" object under the hood. This explains why the object constructor and the "error" function accept mostly the same inputs: they both need error information to perform their jobs.
The two terms "error" and "exception" have very similar meanings, though they are targeted at different audiences. Exception is more of a software developer term while error is less of a jargon for users who are not software developers but are scientists and engineers who are using MATLAB to perform computations.
Regarding the two documentation pages to which you linked, note that the Error Handling page is located in the general programming documentation, while the Exception Handling page is in the advanced software development section. This reflects the fact that "error" is the more basic tool that you should use in general, but that if you are doing something more advanced you may need to know about and work with "MException" objects.

  4 Comments

Show 1 older comment
There are a number of cases in MATLAB where two different routines are provided that have the same thing underneath. For example, rng() is a convenience function to access the Random Streams interface. Lots of the graphics functions just check arguments and call set(). plot() used to be more or less an interface to line(). There are different ways of setting viewpoints and cameras. And so on.
MATLAB is addressed to a number of different audiences that might know the same basic concepts in different names or different emphasis. MATLAB deals with that by providing multiple interfaces to the same functionality, and does not try to force people to think in terms of "The One True Name". If people find it easier to deal with error() then let them have error(), as long as the documentation is consistent.
I partially agree with your perspective. I agree that it is good to acknowledge as much of the audience as possible, and that having multiple convenience/wrapper functions can be useful, but I do not believe it should be done at the expense of confusing or ambiguous functionality. There is definitely a way to continue to support the error() function for those who find it easier to read the word "error" as opposed to "throw", while at the same time providing users enough information about what is happening behind the scenes to make an educated decision about which method to use.
I suppose we may be both be stating the same thing because at the end of your post you say, "...as long as the documentation is consistent." It is my opinion that the documentation is currently inconsistent and does not provide enough information.
@Leo,
Thanks for clearing that up. Would The MathWorks consider making this a little more explicit in the documentation for try/catch/error/MException? For example, the documentation for catch could be amended to say: "If any statement in a try block generates an error or thows an MException object..."

Sign in to comment.


Answer by per isakson
on 15 Feb 2014

And The MathWorks try hard not to break anybodies code.

  1 Comment

Yes I agree, and that is definitely a good thing, but a function can be deprecated while still being supported. It could simply be noted in the documentation that it is deprecated and not the recommended way.

Sign in to comment.