try, catch

Runs code and handles any error it raises instead of stopping the program.

Category: Programming > Programming Utilities

Syntax

try, statements, catch, handler, end

Runs statements; if an error occurs, runs handler and then continues after end.

try, statements, catch ME, handler, end

Also stores the error as an MException in the variable ME for the handler to inspect.

Description

Execution of the try block stops at the first error, skips the rest of that block and jumps to the catch block. If no error occurs, the catch block is skipped. The statements in each block may be on separate lines; try and catch may also be written with commas on a single line.

Inside the handler, the identifier tells which kind of problem occurred, so switch ME.identifier can handle expected ones and rethrow(ME) can pass on the others.

Input arguments

ME
Name of the variable that receives the exception: its identifier, message and other properties describe the error.

Example

Catching an indexing error

x = [1 2 3];
try
    y = x(5);
catch ME
    disp(ME.identifier)
    disp(ME.message)
end
disp('program continues')
Output
MATLAB:badsubscript
Index exceeds the number of array elements. Index must not exceed 3.
program continues

See also

error MException rethrow lasterr onCleanup