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.
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.
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
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.
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.
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.
If you have more message wisdom, post your thoughts here.
댓글을 남기려면 링크 를 클릭하여 MathWorks 계정에 로그인하거나 계정을 새로 만드십시오.