What is Try Catch in Matlab programming language | applied electronics engineering

Latest

What is Try Catch in Matlab programming language

By Applied Electronics - Friday, March 17, 2017 No Comments
The try/catch construct is a special form branching construct designed to trap errors. Ordinarily, when a MATLAB program encounters an error while running, the program aborts. The try/catch construct modifies this default behavior. If an error occurs in a statement in the try block of this construct, then instead of aborting, the code in the catch block is executed and the program keeps running. This allows a programmer to handle errors within the program without causing the program to stop.

The general form of a try/catch construct is as follows:
try
Statement 1
Statement 2 Try Block
...
catch
Statement 1
Statement 2 Catch Block
...
end

When a try/catch construct is reached, the statements in the try block of a will be executed. If no error occurs, the statements in the catch block will be skipped, and execution will continue at the first statement following the end of the construct. On the other hand, if an error does occur in the try block, the program will stop executing the statements in the try block and immediately execute the
statements in the catch block.

An example program containing a try/catch construct follows. This program creates an array and asks the user to specify an element of the array to display. The user will supply a subscript number, and the program displays the corresponding array element. The statements in the try block will always be
executed in this program, while the statements in the catch block will be executed only if an error occurs in the try block.

% Initialize array
a = [ 1 -3 2 5];
try
% Try to display an element
index = input('Enter subscript of element to display: ');
disp( ['a(' int2str(index) ') = ' num2str(a(index))] );
catch
% If we get here an error occurred
disp( ['Illegal subscript: ' int2str(index)] );
end

When this program is executed, the results are as follows:
» try_catch
Enter subscript of element to display: 3
a(3) = 2
» try_catch
Enter subscript of element to display: 8
Illegal subscript: 8

This example is from the book MATLAB Programming for Engineers. See also the book Download Essential Matlab for Enginner and Scientist PDF ebook free.

Tags:

No Comment to " What is Try Catch in Matlab programming language "