Programming Previous page   Next Page

Handling and Recovering from an Error

The catch segment of a try-catch block needs to effectively handle any errors that may be caught by the preceding try. Frequently, you will want to simply report the error and stop execution. This prevents erroneous data from being propagated into the remainder of the program.

Reporting an Error

To report an error and halt program execution, use the MATLAB error function. You determine what the error message will be by specifying it as an input to the error function in your code. For example,

displays the message shown below when n is equal to zero.

Formatted Message Strings

The error message string that you specify can also contain formatting conversion characters, such as those used with the MATLAB sprintf function. Make the error string the first argument, and then add any variables used by the conversion as subsequent arguments.

For example, if your program cannot find a specific file, you might report the error with

Message Identifiers

Use a message identifier argument with error to attach a unique tag to that error message. MATLAB uses this tag to better identify the source of an error. The first argument in this example is the message identifier.

See Using Message Identifiers with lasterr for more information on how to use identifiers with errors.

Formatted String Conversion

MATLAB converts special characters (like \n and %d) in the error message string only when you specify more than one input argument with error. In the single argument case shown below, \n is taken to mean backslash-n. It is not converted to a newline character.

But, when more than one argument is specified, MATLAB does convert special characters. This is true regardless of whether the additional argument supplies conversion values or is a message identifier.


Previous page  Nested try-catch Blocks Identifying the Cause Next page

© 1994-2005 The MathWorks, Inc.