Programming |
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
:
try
segment are executed normally, just as if they were in the regular code flow. But if any of these operations result in an error, MATLAB skips the remaining statements in the try
and jumps to the catch
segment of the block.
catch
segment handles the error. In this example, it displays a general error message. If there are different types of errors that can occur, you will want to identify which error has been caught and respond to that specific error. You can also try to recover from an error in the catch
section.
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.
Note
Faulty error statements executed within a try block are not caught, but instead cause MATLAB to abort the M-file.
|
Error Handling | Nested try-catch Blocks |
© 1994-2005 The MathWorks, Inc.