Respond to an Exception
In this section...
“Overview” on page 26-19
“The try/catch Statement” on page 26-19
“Suggestions on How to Handle an Exception” on page 26-21
Overview
The MATLAB software, by default, terminates the currently running program when an
exception is thrown. If you catch the exception in your program, however, you can
capture information about what went wrong and deal with the situation in a way that is
appropriate for the particular condition. This requires a try/catch statement.
The try/catch Statement
When you have statements in your code that could generate undesirable results, put
those statements into a try/catch block that catches any errors and handles them
appropriately.
A try/catch statement looks something like the following pseudocode. It consists of two
parts:
- A try block that includes all lines between the try and catch statements.
- A catch block that includes all lines of code between the catch and end statements.
try
Perform one ...
or more operations
A catch ME
Examine error info in exception object ME
Attempt to figure out what went wrong
Either attempt to recover, or clean up and abort
end
B Program continues
The program executes the statements in the try block. If it encounters an error, it skips
any remaining statements in the try block and jumps to the start of the catch block
Respond to an Exception