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:

The eval function provides error-handling capabilities using the two- argument form

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.

This example uses the two-argument form of eval with the catchfcn function shown above.


 Empty Matrices Displaying Error and Warning Messages