Skip to content

MATLAB - Try...Catch statement

MATLAB - Robust Error Handling with try...catch

Section titled “MATLAB - Robust Error Handling with try...catch”

Robust error handling is a cornerstone of professional software development. In MATLAB, the try...catch statement allows you to anticipate and manage potential errors (exceptions) during code execution, preventing your program from crashing and enabling you to respond gracefully.

try
% Code that might generate an error
statements_to_try
catch exception
% Code to execute if an error occurs in the try block
error_handling_statements
end
  1. MATLAB executes the code within the try block.
  2. If no error occurs, the catch block is skipped entirely.
  3. If an error does occur in the try block, MATLAB immediately stops execution of the try block and jumps to the catch block.
  4. The catch block is executed. The exception variable, which is an MException object, contains detailed information about the error.

The exception variable is the key to effective error handling. It has several useful properties:

  • exception.identifier: A unique string identifying the error type (e.g., 'MATLAB:UndefinedFunction', 'MATLAB:badsubscript'). Ideal for programmatic error checking.
  • exception.message: A user-friendly string describing the error.
  • exception.stack: A struct array containing the function call stack at the time of the error (file, name, line number). Invaluable for debugging.
  • exception.cause: A cell array of other MException objects that may have caused this one, useful for nested exceptions.

Example 1: Handling Specific Errors with a switch

Section titled “Example 1: Handling Specific Errors with a switch”

A powerful pattern is to use a switch statement on the exception.identifier to handle different types of errors differently.

myArray = [10, 20, 30];
indexToAccess = 5; % This will cause an error
try
fprintf('Attempting to access element %d...\n', indexToAccess);
value = myArray(indexToAccess);
fprintf('Value is: %d\n', value);
catch exception
fprintf('An error occurred!\n');
% Handle different errors in different ways
switch exception.identifier
case 'MATLAB:badsubscript'
fprintf('Error Type: Index out of bounds.\n');
fprintf('Message: %s\n', exception.message);
fprintf('The array has only %d elements.\n', numel(myArray));
otherwise
% For any other error, we rethrow it because we don't know how to handle it
fprintf('An unexpected error occurred. Rethrowing.\n');
rethrow(exception);
end
end

When you run this code, the output is:

Attempting to access element 5...
An error occurred!
Error Type: Index out of bounds.
Message: Index exceeds the number of array elements. Index must not exceed 3.
The array has only 3 elements.

Resource Management: The finally Pattern with onCleanup

Section titled “Resource Management: The finally Pattern with onCleanup”

While MATLAB does not have a finally keyword like Java or Python, it provides a more powerful mechanism: the onCleanup object. This object executes a function handle when it goes out of scope, either normally or due to an error. This guarantees that cleanup code (like closing a file) will run.

This example demonstrates a robust way to read from a file, ensuring it is always closed.

function data = robustReadFile(filename)
% Attempts to read data from a file, ensuring it's always closed.
fileID = -1; % Initialize to an invalid file identifier
try
fileID = fopen(filename, 'r');
if fileID == -1
% Create and throw a custom error if file can't be opened
error('ROBUSTREAD:FileNotFound', 'File ''%s'' could not be opened.', filename);
end
% Set up the cleanup task. This will run when the function exits for any reason.
cleanupTask = onCleanup(@() fclose(fileID));
fprintf('File ''%s'' opened successfully.\n', filename);
% ... Process the file (here we just read one line as an example) ...
data = fgetl(fileID);
fprintf('Data read successfully.\n');
% Let's simulate an error during processing
% error('ROBUSTREAD:ProcessingError', 'A simulated processing error occurred!');
catch exception
fprintf('Caught an error: %s\n', exception.message);
% Re-assign the exception to the output so the caller can inspect it
data = exception;
end
% The cleanupTask (fclose) is automatically executed here
fprintf('Function exiting. File should be closed now.\n');
end

You can test this function with robustReadFile('mydata.txt'). Even if an error occurs after fopen, the onCleanup object guarantees fclose(fileID) is called.

  • Be Specific: Catch the errors you can actually handle. Avoid generic catch blocks that hide unexpected problems. Use rethrow(exception) for errors you cannot handle.
  • Use onCleanup for Resources: For any resource that needs to be explicitly released (files, hardware connections, etc.), use onCleanup to guarantee it happens.
  • Provide Context: When you throw your own errors, use a descriptive identifier and message. This helps you and other users of your code to debug issues efficiently.
  • Don’t Suppress Errors Silently: Avoid empty catch blocks. At a minimum, display a warning (warning(...)) or log the error for later review.