Documentation Center

  • Trial Software
  • Product Updates

Use try/catch to Handle Errors

You can use a try/catch statement to execute code after your program encounters an error. try/catch statements can be useful if you:

  • Want to finish the program in another way that avoids errors

  • Need to clean up unwanted side effects of the error

  • Have many problematic input parameters or commands

Arrange try/catch statements into blocks of code, similar to this pseudocode:

  try block...
  catch block...

If an error occurs within the try block, MATLAB® skips any remaining commands in the try block and executes the commands in the catch block. If no error occurs within try block, MATLAB skips the entire catch block.

For example, a try/catch statement can prevent the need to throw errors. Consider the combinations function that returns the number of combinations of k elements from n elements:

function com = combinations(n,k)
    com = factorial(n)/(factorial(k)*factorial(n-k));

MATLAB throws an error whenever k > n. You cannot construct a set with more elements, k, than elements you possess, n. Using a try/catch statement, you can avoid the error and execute this function regardless of the order of inputs:

function com = robust_combine(n,k)
       com = factorial(k)/(factorial(n)*factorial(k-n));

robust_combine treats any order of integers as valid inputs:

C1 = robust_combine(8,4)
C2 = robust_combine(4,8)
C1 =


C2 =


MATLAB might give you a code analyzer message: Line 4: Best practice is for CATCH to be followed by an identifier that gets the error information. This message indicates that you can capture more information about errors if a variable follows your catch statement:

catch MExc

MExc is an MException class object that contains more information about the thrown error. To learn more about accessing information from MException objects, see Exception Handling in a MATLAB Application.

See Also


Was this topic helpful?