Error Handling in MATLAB
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
, catch
blocks for error handling. The code within the try
block is executed, and if an error occurs, control is passed to the catch
block.
% Example of try-catch
try
A = [1 2 3; 4 5]; % This will throw an error due to mismatched dimensions
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 generate custom errors using 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.");
If y
is zero, the program stops and outputs the assertion message:
Assertion failed.
AssertionFailed:ZeroDivision
y cannot be zero.
Advanced Error Handling
For more complex workflows, MATLAB allows you to use MException
objects to capture and analyze error details.
% Capturing error information
try
A = [1, 2] / 0; % This will generate 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 allows you to define cleanup tasks that will run when a function exits, regardless of whether it exits normally or due to 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 will be properly closed because of the onCleanup
function.
Useful MATLAB Functions for Error Handling
Practice Questions
Test Yourself
1. Write a script that checks if a user-entered value is a positive integer. If not, throw a custom error.
2. Create a function that divides two numbers. Use try...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 to capture the error details using MException
and display them.