A Little Bit on Message Handling
This is a quick note about handling errors and warnings in MATLAB. In particular, the function error has a couple of aspects that people sometimes trip over or overlook.
Contents
What error Does
The main thing error is responsible for is issuing a message to the user that he or she has done something incorrectly. The first place you might see error checking in a function is looking at the input arguments. Using nargchk is a common way to see if there's a problem and then calling error afterwards.
Sample Snippet
Let's see one pattern. Here we are checking that the number of inputs, narg, lies between 2 and 7. If not, we'll issue an error.
narg = 4; msg = nargchk(2,7,narg,'struct'); if ~isempty(msg) error(msg) end
It turns out, this code is more complex than necessary. We can equivalently write
error(nargchk(2,7,narg,'struct'));
because the function error does not produce an error with empty input. This is a gotcha that people occasionally run into. You can't just use a simple statement like error('') to signal an error in your code.
Why Use the 'struct' Option?
I am using the 'struct' argument for nargchk so the output is a structure with both a message identifier and the message itself. Why? Because I, as the application developer, could choose to issue a different message or take a different action, e.g., using a try-catch construct. Using message identifiers for warning users about something allows the users to control that specific warning. Perhaps, after seeing it once, a user might want to turn that warning off, but would still like to be alerted of other possible issues.
Another gotcha
Users are also occasionally tripped by turning a particular warning off, running some other code, and then not expecting to see the turned off warning showing up when they use lastwarn to see if something has happened. Depending on the sequence of events, it's possible that lastwarn will return a message from a warning that was turned off. warning off ID simply turns off the display of the warning message.
Any More Message Wisdom?
If you have more message wisdom, post your thoughts here.
- Category:
- Common Errors