Main Content

try, catch

Execute statements and catch resulting errors

Syntax

try
   statements
catch exception
   statements
end

Description

example

try statements, catch statements end executes the statements in the try block and catches resulting errors in the catch block. This approach allows 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 MException object that allows you to identify the error. The catch block assigns the current exception object to the variable in exception.

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

Examples

collapse all

Create two matrices that you cannot concatenate vertically.

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

C = [A; B];
Error using vertcat
Dimensions of matrices being concatenated are not consistent.

Use try/catch to display more information about the dimensions.

try
   C = [A; B];
catch ME
   if (strcmp(ME.identifier,'MATLAB:catenate:dimensionMismatch'))
      msg = ['Dimension mismatch occurred: First argument has ', ...
            num2str(size(A,2)),' columns while second has ', ...
            num2str(size(B,2)),' columns.'];
        causeException = MException('MATLAB:myCode:dimensions',msg);
        ME = addCause(ME,causeException);
   end
   rethrow(ME)
end 
Error using vertcat
Dimensions of matrices being concatenated are not consistent.

Caused by:
    Dimension mismatch occurred: First argument has 3 columns while second has 5 columns.

If matrix dimensions do not agree, MATLAB® displays more information about the mismatch. Any other errors appear as usual.

Catch any exception generated by calling the nonexistent function, notaFunction. If there is an exception, issue a warning and assign the output a value of 0.

try
    a = notaFunction(5,6);
catch
    warning('Problem using function.  Assigning a value of 0.');
    a = 0;
end
Warning: Problem using function.  Assigning a value of 0.

By itself, the call to notaFunction results in an error. If you use try and catch, this code catches any exception and repackages it as a warning, allowing MATLAB to continue executing subsequent commands.

Use try/catch to handle different types of errors in different ways.

  • If the function notaFunction is undefined, issue a warning instead of an error and assign the output a value of NaN.

  • If notaFunction.m exists, but is a script instead of a function, issue a warning instead of an error, run the script, and assign the output a value of 0.

  • If MATLAB throws an error for any other reason, rethrow the exception.

try
    a = notaFunction(5,6);
catch ME
    switch ME.identifier
        case 'MATLAB:UndefinedFunction'
            warning('Function is undefined.  Assigning a value of NaN.');
            a = NaN;
        case 'MATLAB:scriptNotAFunction'
            warning(['Attempting to execute script as function. '...
                'Running script and assigning output a value of 0.']);
            notaFunction;
            a = 0;
        otherwise
            rethrow(ME)
    end
end
Warning: Function is undefined.  Assigning a value of NaN. 

Tips

  • You cannot use multiple catch blocks within a try block, but you can nest complete try/catch blocks.

  • Unlike some other languages, MATLAB does not allow the use of a finally block within try/catch statements.

Extended Capabilities

Version History

Introduced before R2006a

expand all