Academic Block

Error Handling in MATLAB Get Certified

Error handling is a critical aspect of programming that ensures your code can gracefully handle unexpected conditions or inputs. MATLAB provides several mechanisms and functions to detect, manage, and resolve errors.

Basic Concepts of Error Handling

MATLAB uses the try \ldots catch blocks for error handling. The code inside the try block is executed; if an error occurs, control is transferred to the catch block.

% Example of try-catch
try
    A = [1 2 3; 4 5];   % mismatched dimensions will raise an error
catch exception
    disp("An error occurred:");
    disp(exception.message);
end

Output:

An error occurred:
Dimensions of arrays being concatenated are not consistent.

Generating Custom Errors

You can raise your own errors with the error or assert functions.

% Example of generating a custom error
x = -5;
if x < 0
    error("CustomError:NegativeValue", "The value of x cannot be negative.");
end

Output:

CustomError:NegativeValue
The value of x cannot be negative.
% Using assert for condition checks
y = 0;
assert(y ~= 0, "AssertionFailed:ZeroDivision", "y cannot be zero.");

When y is zero the program stops and displays:

Assertion failed.
AssertionFailed:ZeroDivision
y cannot be zero.

Advanced Error Handling

For more complex workflows MATLAB lets you capture and examine the full MException object.

% Capturing error information
try
    A = [1, 2] / 0;          % generates an error
catch ME
    disp("Error ID: " + ME.identifier);
    disp("Error Message: " + ME.message);
end

Output:

Error ID: MATLAB:dimagree
Error Message: Array dimensions must match for binary array op.

Using onCleanup for Resource Management

The onCleanup function lets you register a cleanup task that will run when a function (or script) exits, whether the exit is normal or caused by an error.

% Using onCleanup for resource management
fid = fopen('example.txt', 'w');
cleanup = onCleanup(@() fclose(fid));
fprintf(fid, 'This will be written to the file.');
error("SimulatedError", "An error occurred before fclose.");

Even though an error occurs, the file is properly closed because of the onCleanup object.

Useful MATLAB Functions for Error Handling

Function
Explanation
error
Generates an error and stops execution.
assert
Throws an error if a condition is not true.
try \ldots catch
Handles errors in a controlled manner.
lastwarn
Retrieves the last warning message issued.
lasterror
Retrieves information about the last error (older style).
onCleanup
Specifies cleanup tasks that run when a function exits.

Practice Questions

Test Yourself

1. Write a script that checks whether a user-entered value is a positive integer. If not, throw a custom error.

2. Create a function that divides two numbers. Use try\ldots catch to handle division by zero.

3. Write a script that opens a file, writes to it, and ensures the file is closed even if an error occurs.

4. Modify the script in Question 3 so that it captures the error details with an MException object and displays them.