Should M-Lint Try to Make a Recommendation?
At The MathWorks, we continue to explore ways to ease your programming learning curve and help you write better code. As such, we have been discussing how stringent to make the messages in mlint with respect to catching errors. Currently, MATLAB doesn't make any particular recommendation about checking to be sure you know which error you got before moving forward. Is that a really good idea? We aren't sure and thought find out your thoughts on this.
Contents
An Example
Let me show you two snippets of code trying to accomplish basically the same task. I will discuss pros and cons of each. Note, I will be using the new MException syntax for try and catch though you can do similar things using the older lasterror mechanism as well.
Snippet #1
try doSomething; doMore; catch myException cleanUpHere; maybeThrowOwnNewException; end
Snippet #2
try doSomething; doMore; catch myException expectedExceptionID = 'MATLAB:dimagree'; if strcmp(myException.identifier,expectedExceptionID) cleanUpHereAndMaybeThrowError; else doDifferentCleanUp; throwUnexpectedException; end end
Pros and Cons
- snippet #1 is shorter than snippet #2
- snippet #1 never checks that the caught error is the expected one
- snippet #2 does two different operations, depending on whether the error was expected or not
- when snippet #1 does throw its own new exception, since it didn't look at the actual one, the cause may not be correct or meaningful to the user
There's No catch
Another related question arises if the try is not paired with a catch.
What Do You Think M-Lint Should Do?
For the first example, neither code snippet is outright "wrong." Moreover, there are cases, no doubt, where no matter what the actual error is, you have no choice but to do a particular set of operations. However, that clearly isn't always so. So, how forceful would you like to see M-Lint be for the case of snippet #1? Would getting a message there (though not a red one) be helpful?
What about the situation in which there is no catch accompanying the try? Again, there may be a few cases where this makes sense, but typically that won't be so.
Let us know your thoughts about these questions here.
- Category:
- Best Practice,
- Common Errors,
- Robustness