Main Content

Respond to an Exception

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 (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: 49

Note

You cannot define nested functions within a try or catch block.

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 catch block.

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. ME is an MException object. When an exception occurs, MATLAB creates an MException object 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.

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.

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)

% 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.

  • Compare the identifier field of the MException object 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/catch statement 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 MException object to the cause field of the second.

  • Add a suggested correction to an MException object.

  • 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.