Programming Previous page   Next Page

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.

Previous page  Error Handling Nested try-catch Blocks Next page

© 1994-2005 The MathWorks, Inc.