Programming and Data Types |
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
:
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.
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.
trystatement1
% Try to execute statement1 catch trystatement2
% Attempt to recover from error catch disp 'Operation failed' % Handle the error end end
Empty Matrices | Handling and Recovering from an Error |