Programming |
Identifying the Cause
Once an error has been caught, you will need to know the source of the error in order to handle it appropriately. The lasterr
function returns information that enables you to identify the error that was most recently generated by MATLAB.
To return the most recent error message to the variable errormsg
, type
You can also change the text of the last error message with a new message or with an empty string as shown below. You might want to do this if a lower level routine detects an error that you don't want visible to the upper levels.
lasterr('newerrormsg
'); % Replace last error with new string
lasterr(''); % Replace last error with empty string
Example Using lasterr
The matrixMultiply
function shown earlier in this section could fail for various reasons. If it is called with incompatible matrices, for example, lasterr
returns the following string.
This example uses lasterr
to determine the cause of an error in matrixMultiply
.
function matrixMultiply(A, B) try A * B catch errmsg = lasterr; if(strfind(errmsg, 'Inner matrix dimensions')) disp('** Wrong dimensions for matrix multiply') else if(strfind(errmsg, 'not defined for variables of class')) disp('** Both arguments must be double matrices') end end end
When calling the function with two matrices not compatible for matrix multiplication, you get the following error message.
A = [1 2 3; 6 7 2; 0 1 5]; B = [9 5 6; 0 4 9]; matrixMultiply(A, B) ** Wrong dimensions for matrix multiply
When calling the function with a cell array argument, you get a message that addresses that error.
Handling and Recovering from an Error | Regenerating an Error |
© 1994-2005 The MathWorks, Inc.