Programming and Data Types    

Errors and Warnings

In many cases, it is desirable to take specific actions when different kinds of errors occur. For example, you may want to prompt the user for more input, display extended error or warning information, or repeat a calculation using default values. The error handling capabilities in MATLAB let your application check for particular error conditions and execute appropriate code depending on the situation.

This section covers the following topics:

Checking for Errors with try-catch

No matter how carefully you plan and test the programs you write, they may not always run as smoothly as expected when run under different conditions. It is always a good idea to include error checking in programs to ensure reliable operation under all conditions.

When you have statements in your code that could possibly generate unwanted results, put those statements into a try-catch block that will catch any errors and handle them appropriately. The example below shows a try-catch block within a sample function that multiplies two matrices:

A try-catch block is divided into two sections. The first begins with try and the second with catch. Terminate the block with end:

When you execute the above example with inputs that are incompatible for matrix multiplication (e.g., the column dimension of A is not equal to the row dimension of B), MATLAB catches the error and displays the message generated in the catch section of the try-catch block.

Nested try-catch Blocks

You can also nest try-catch blocks, as shown here. You can use this to attempt to recover from an error caught in the first try section.


  Empty Matrices Handling and Recovering from an Error