Programming and Data Types | ![]() ![]() |
Errors and Warnings
In many cases, it's desirable to take specific actions when different kinds of errors occur. For example, you may want to prompt the user for more input, display extended error or warning information, or repeat a calculation using default values. MATLAB's error handling capabilities let your application check for particular error conditions and execute appropriate code depending on the situation.
Error Handling with eval and lasterr
The basic tools for error-handling in MATLAB are:
eval
function, which lets you execute a function and specify a second function to execute if an error occurs in the first.lasterr
function, which returns a string containing the last error generated by MATLAB.The eval
function provides error-handling capabilities using the two- argument form
eval ('trystring','catchstring')
If the operation specified by trystring
executes properly, eval
simply returns. If trystring
generates an error, the function evaluates catchstring. Use catchstring to specify a function that determines the error generated by trystring
and takes appropriate action.
The trystring
/catchstring
form of eval
is especially useful in conjunction with the lasterr
function. lasterr
returns a string containing the last error message generated by MATLAB. Use lasterr
inside the catchstring
function to "catch" the error generated by trystring
.
For example, this function uses lasterr
to check for a specific error message that can occur during matrix multiplication. The error message indicates that matrix multiplication is impossible because the operands have different inner dimensions. If the message occurs, the code truncates one of the matrices to perform the multiplication.
function C = catchfcn(A,B)
l = lasterr;
j = findstr(l,'Inner matrix dimensions')
if (~isempty(j))
[m,n] = size(A)
[p,q] = size(B)
if (n>p)
A(:,p+1:n) = []
elseif (n<p)
B(n+1:p,:) = []
end
C = A*
B;
else
C = 0;
end
This example uses the two-argument form of eval
with the catchfcn
function shown above.
clear A = [1 2 3; 6 7 2; 0 1 5]; B = [9 5 6; 0 4 9]; eval('A*
B','catchfcn(A,B)') A = 1:7; B = randn(9,9); eval('A*
B','catchfcn(A,B)')
![]() | Empty Matrices | Displaying Error and Warning Messages | ![]() |