Having entered the catch block, MATLAB executes the statements in sequence. These
statements can attempt to
- Attempt to resolve the error.
- Capture more information about the error.
- Switch on information found in the MException object and respond appropriately.
- Clean up the environment that was left by the failing code.
The catch block often ends with a rethrow command. The rethrow causes MATLAB to
exit the current function, keeping the call stack information as it was when the exception
was first thrown. If this function is at the highest level, that is, it was not called by
another function, the program terminates. If the failing function was called by another
function, it returns to that function. Program execution continues to return to higher level
functions, unless any of these calls were made within a higher-level try block, in which
case the program executes the respective catch block.
More information about the MException class is provided in the section “Capture
Information About Exceptions” on page 26-5.
Suggestions on How to Handle an Exception
The following example reads the contents of an image file. It includes detailed error
handling, and demonstrates some suggested actions you can take in response to an error.
The image-reading function throws and catches errors in several ways.
- The first if statement checks whether the function is called with an input argument. If
no input argument is specified, the program throws an error and suggests an input
argument to correct the error. - The try block attempts to open and read the file. If either the open or the read fails,
the program catches the resulting exception and saves the MException object in the
variable ME1. - The catch block checks to see if the specified file could not be found. If so, the
program allows for the possibility that a common variation of the filename extension
(e.g., jpeg instead of jpg) was used, by retrying the operation with a modified
extension. This is done using a try/catch statement nested within the original try/
catch.
function d_in = read_image(filename)
Respond to an Exception