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.
This section covers the following topics:
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 (shown here as point A
). If
all operations in the try
block succeed, then execution skips
the catch
block entirely and goes to the first line following
the end
statement (point B
).
Specifying the try
, catch
, and
end
commands and also the code of the
try
and catch
blocks 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 try
or
catch
block.
On execution, your code enters the try
block and executes
each statement as if it were part of the regular program. If no errors are
encountered, MATLAB skips the catch
block entirely and continues
execution following the end
statement. If any of the
try
statements fail, MATLAB immediately exits the try
block, leaving any
remaining statements in that block unexecuted, and enters the
catch
block.
The catch
command marks the start of a
catch
block and provides access to a data structure that
contains information about what caused the exception. This is shown as the
variable ME
in the preceding pseudocode. This data structure
is an object of the MATLAB
MException
class. 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 catch
statement. If you do not need any of the information or methods provided by the
MException
object, just specify the
catch
keyword alone.
The 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 MException
object 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
MException
class.
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.
The following example reads the contents of an image file. The
try
block attempts to open and read the file. If either the
open or read fails, the program catches the resulting exception and saves the
MException
object in the variable
ME1
.
The 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 (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) [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:
Compare the identifier
field of the
MException
object against possible causes of the
error.
Use a nested try/catch
statement to retry the open and
read operations using a known variation of the filename extension.
Display an appropriate message in the case that the file truly does not exist and then rethrow the exception.
Add the first MException
object to the
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.