Products & Services Solutions Academia Support User Community Company

Learn more about MATLAB   

try - Execute statements and catch resulting errors

Syntax

try

Description

try marks the beginning of a try-catch statement, a two-part sequence of commands used in detecting and handling errors. The try-catch enables you to bypass default error handling for selected segments of your program code and use your own procedures instead. The two parts of a try-catch statement are a try block and a catch block (see the figure below). The try block begins with the try command and ends just before to the catch command:

try                          try block
   program-code                  |
   program-code                  |
       :                         V
catch exception             catch block
   error-handling code           |
       :                         |
   rethrow(exception)            V
end

The try block contains one or more commands for which special error handling is required by your program. Any error detected while executing statements in the try block immediately turns program control over to the catch block. Code in the catch block provides error handling that specifically addresses errors that might originate from statements in the preceding try block.

Both the try and catch blocks may contain additional try-catch statements nested within them.

See The try-catch Statement in the Programming Fundamentals documentation for more information.

Remarks

Specifying the try, catch, and end commands, as well as the commands that make up 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.

Examples

Example 1

The first part of this example attempts to vertically concatenate two matrices that have an unequal number of columns:

A = rand(5,3);   B = rand(5,4);
C = [A; B];
??? Error using ==> vertcat
CAT arguments dimensions are not consistent.

Using a try-catch statement, you can provide more information about what went wrong:

try
   C = [A; B];
catch exception
   if strcmp(exception.identifier, ...
      'MATLAB:catenate:dimensionMismatch')
      [~, colA] = size(A);   [~, colB] = size(B);
      disp(exception.message);
      fprintf('Matrix A has %d columns while matrix B has %d\n', ...
          colA, colB);
   end
end

Running the program displays the following message:

CAT arguments dimensions are not consistent.
Matrix A has 3 columns while matrix B has 4

Example 2

The catch block in this example checks to see if the specified file could not be found. If this is the case, 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 that is 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 exception1 
   % Get last segment of the error message identifier.
   idSegLast = regexp(exception1.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(exception1);
      end 

      % Try again, with modifed filenames.
      try
         fid = fopen(filename, 'r'); 
         d_in = fread(fid);
      catch exception2
         fprintf('Unable to access file %s\n', filename);
         exception2 = addCause(exception2, exception1);
         rethrow(exception2)
      end 
   end 
end

See Also

catch, error, assert, MException, throw(MException), rethrow(MException), throwAsCaller(MException), addCause(MException), getReport(MException), last(MException), eval, evalin

  


Recommended Products

Includes the most popular MATLAB recorded presentations with Q&A sessions led by MATLAB experts.

 © 1984-2009- The MathWorks, Inc.    -   Site Help   -   Patents   -   Trademarks   -   Privacy Policy   -   Preventing Piracy   -   RSS