As stated earlier, 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
This section covers the following topics:
When you have statements in your code that could generate undesirable
results, put those statements into a
that catches any errors and handles them appropriately.
try/catch statement looks something like
the following pseudocode. It consists of two parts:
try block that includes all lines
catch block that includes all
lines of code between the
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
If it encounters an error, it skips any remaining statements in the
and jumps to the start of the
catch block (shown
here as point
A). If all operations in the
succeed, then execution skips the
entirely and goes to the first line following the
end commands and also the code of the
on separate lines is recommended. If you combine any of these components
on the same line, separate them with commas:
try, surf, catch ME, ME.stack, end ans = file: 'matlabroot\toolbox\matlab\graph3d\surf.m' name: 'surf' line: 54
You cannot define nested functions within a
On execution, your code enters the
and executes each statement as if it were part of the regular program.
If no errors are encountered, MATLAB skips the
entirely and continues execution following the
If any of the
try statements fail, MATLAB immediately
try block, leaving any remaining statements
in that block unexecuted, and enters the
catch command marks the start of a
and provides access to a data structure that contains information
about what caused the exception. This is shown as the variable
the preceding pseudocode. This data structure is an object of the MATLAB
When an exception occurs, MATLAB constructs an instance of this
class and returns it in the
catch statement that
handles that error.
You are not required to specify any argument with the
If you do not need any of the information or methods provided by the
just specify the
catch keyword alone.
MException object is constructed by internal
code in the program that fails. The object has properties that contain
information about the error that can be useful in determining what
happened and how to proceed. The
also provides access to methods that enable you to respond to the
exception. See the section on The MException Class to find out more about the
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
and respond appropriately.
Clean up the environment that was left by the failing code.
catch block often ends with a
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
in which case the program executes the respective catch block.
More information about the
is provided in the section Capture Information About
The following example reads the contents of an image file. The
attempts to open and read the file. If either the open or read fails,
the program catches the resulting exception and saves the
in the variable
catch block in the example 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
jpeg instead of
was used by retrying the operation with a modified extension. This
is done using a
try/catch statement nested within
function d_in = read_image(filename) [path name ext] = fileparts(filename); try fid = fopen(filename, 'r'); d_in = fread(fid); catch ME1 % Get last segment of the error message identifier. idSegLast = regexp(ME1.identifier, '(?<=:)\w+$', 'match'); % Did the read fail because the file could not be found? if strcmp(idSegLast, 'InvalidFid') && ... ~exist(filename, 'file') % Yes. Try modifying the filename extension. switch ext case '.jpg' % Change jpg to jpeg filename = strrep(filename, '.jpg', '.jpeg') case '.jpeg' % Change jpeg to jpg filename = strrep(filename, '.jpeg', '.jpg') case '.tif' % Change tif to tiff filename = strrep(filename, '.tif', '.tiff') case '.tiff' % Change tiff to tif filename = strrep(filename, '.tiff', '.tif') otherwise fprintf('File %s not found\n', filename); rethrow(ME1); end % Try again, with modifed filenames. try fid = fopen(filename, 'r'); d_in = fread(fid); catch ME2 fprintf('Unable to access file %s\n', filename); ME2 = addCause(ME2, ME1); rethrow(ME2) end end end
This example illustrates some of the actions that you can take in response to an exception:
identifier field of
MException object against possible causes of
Use a nested
to retry the open and read operations using a known variation of the
Display an appropriate message in the case that the file truly does not exist and then rethrow the exception.
Add the first
cause field of the second.
Rethrow the exception. This stops program execution and displays the error message.
Cleaning up any unwanted results of the error is also advisable. For example, your program may have allocated a significant amount of memory that it no longer needs.