Respond to an Exception
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
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.
try/catch statement looks something like the following
pseudocode. It consists of two parts:
tryblock that includes all lines between the
catchblock 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
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
all operations in the
try block succeed, then execution skips
catch block entirely and goes to the first line following
end statement (point
end commands and also the code of the
catch blocks on separate lines is
recommended. If you combine any of these components on the same line, separate them
try, surf, catch ME, ME.stack, end ans = file: 'matlabroot\toolbox\matlab\graph3d\surf.m' name: 'surf' line: 49
You cannot define nested functions within a
The Try 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
The Catch Block
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
ME in the preceding pseudocode.
ME is an
MException object. When an
exception occurs, MATLAB creates an
MException object and returns it in
catch statement that handles that error.
You are not required to specify any argument with the
statement. If you do not need any of the information or methods provided by the
MException object, 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.
MException object also provides access to methods that
enable you to respond to the exception.
Having entered the
catch block, MATLAB executes the statements in sequence. These statements can attempt
Attempt to resolve the error.
Capture more information about the error.
Switch on information found in the
MExceptionobject and respond appropriately.
Clean up the environment that was left by the failing code.
catch block often ends with a
rethrow command. The
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.
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.
ifstatement 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.
tryblock attempts to open and read the file. If either the open or the read fails, the program catches the resulting exception and saves the
MExceptionobject in the variable
catchblock 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.,
jpg) was used, by retrying the operation with a modified extension. This is done using a
try/catchstatement nested within the original
function d_in = read_image(filename) % Check the number of input arguments. if nargin < 1 me = MException('MATLAB:notEnoughInputs','Not enough input arguments.'); aac = matlab.lang.correction.AppendArgumentsCorrection('"image.png"'); me = me.addCorrection(aac); throw(me); end % Attempt to read file and catch an exception if it arises. try fid = fopen(filename,'r'); d_in = fread(fid); catch ME1 % Get last segment of the error 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 modified 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.
identifierfield of the
MExceptionobject to possible causes of the error. In this case, the function checks whether the identifier ends in
'InvalidFid', indicating a file could not be found.
Use a nested
try/catchstatement to retry the operation with improved input. In this case, the function retries the open and read operations using a known variation of the filename extension.
Display an appropriate message.
Add the first
MExceptionobject to the
causefield of the second.
Add a suggested correction to an
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, close figures that remained open after the error occurred.