try, catch

Execute statements and catch resulting errors

Syntax

try
   statements
catch exception
   statements
end

Description

try and catch blocks allow you to override the default error behavior for a set of program statements. If any statement in a try block generates an error, program control goes immediately to the catch block, which contains your error handling statements.

exception is an optional MException object input to the catch block that allows you to identify the error.

Both try and catch blocks can contain nested try/catch statements.

Examples

Provide more information about a dimension mismatch error:

A = rand(3);
B = ones(5);

try
   C = [A; B];
catch err

   % Give more information for mismatch.
   if (strcmp(err.identifier,'MATLAB:catenate:dimensionMismatch'))

      msg = ['Dimension mismatch occurred: First argument has ', ...
            num2str(size(A,2)), ' columns while second has ', ...
            num2str(size(B,2)), ' columns.'];
      error('MATLAB:myCode:dimensions', msg);

   % Display any other errors as usual.
   else
      rethrow(err);
   end

end  % end try/catch

Catch an error when reading an image file, and try adjusting the file extension to resolve the error (.jpg and .jpeg are similar, as are .tif and .tiff):

function imageData = readImage(filename)
try
   imageData = imread(filename);
catch exception

   % Is the error because MATLAB could not find the file?
   if ~exist(filename, 'file')

      % Check for common typos in the extension.
      [~, ~, extension] = fileparts(filename);
      switch extension
         case '.jpg'
            altFilename = strrep(filename, '.jpg', '.jpeg');
         case '.jpeg'
            altFilename = strrep(filename, '.jpeg', '.jpg');
         case '.tif'
            altFilename = strrep(filename, '.tif', '.tiff');
         case '.tiff'
            altFilename = strrep(filename, '.tiff', '.tif');
         otherwise 
            rethrow(exception);
      end 

      % Try again, with modifed filename.
      try 
         imageData = imread(altFilename);
      catch exception2
         % Rethrow original error.
         rethrow(exception)
      end 

   else 
      rethrow(exception)
   end

end

See Also

| |

Was this topic helpful?