Accelerating the pace of engineering and science

Documentation Center

• Trials

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
try block...
catch
catch block...
end```

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));
end```

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)
try
com = factorial(n)/(factorial(k)*factorial(n-k));
catch
com = factorial(k)/(factorial(n)*factorial(k-n));
end
end```

robust_combine treats any order of integers as valid inputs:

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

70

C2 =

70```

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`