Error Handling
When something goes wrong, MATLAB raises an error: the program stops and a message is printed. With try/catch you can intercept errors, report them nicely, and recover. With error you raise your own.
try / catch
Code in the try block runs normally. If any statement raises an error, MATLAB jumps straight to the catch block; the rest of the try block is skipped. Without an error, the catch block is skipped:
values = {'12', 'abc', '7.5'};
for k = 1:numel(values)
try
n = parse_number(values{k});
fprintf('%s -> %g\n', values{k}, n);
catch err
fprintf('%s -> error: %s\n', values{k}, err.message);
end
end
disp('The program keeps running.')
function n = parse_number(s)
n = str2double(s);
if isnan(n)
error('parse:notNumber', '"%s" is not a number', s);
end
end12 -> 12
abc -> error: "abc" is not a number
7.5 -> 7.5
The program keeps running.
catch err stores information about the error in err (an MException object in MATLAB; a struct with the same fields in Octave).
The error object
| Field | Contains |
|---|---|
err.message |
The error text |
err.identifier |
An ID like 'parse:notNumber' (may be empty) |
err.stack |
Where the error happened (file, function, line) |
Identifiers let you react differently to different errors:
inputs = {[1 2 3], 'text', -4};
for k = 1:numel(inputs)
try
r = safe_sqrt_sum(inputs{k});
fprintf('result: %g\n', r);
catch err
switch err.identifier
case 'sqrtsum:type'
disp('Please pass numbers.')
case 'sqrtsum:negative'
disp('Negative values are not allowed.')
otherwise
rethrow(err); % unexpected: pass it on
end
end
end
function r = safe_sqrt_sum(v)
if ~isnumeric(v)
error('sqrtsum:type', 'Input must be numeric.');
end
if any(v < 0)
error('sqrtsum:negative', 'Input must be non-negative.');
end
r = sum(sqrt(v));
endresult: 4.14626
Please pass numbers.
Negative values are not allowed.
An identifier has the form component:mnemonic (at least one colon). rethrow(err) re-raises an error you don't know how to handle, so it isn't silently swallowed.
Raising errors
error(msg) or error(id, format, values...) stops the current function and raises an error. The format works like sprintf:
try
withdraw(100, 250);
catch err
fprintf('[%s] %s\n', err.identifier, err.message);
end
function balance = withdraw(balance, amount)
if amount > balance
error('bank:insufficientFunds', ...
'Cannot withdraw %.2f: balance is only %.2f', amount, balance);
end
balance = balance - amount;
end[bank:insufficientFunds] Cannot withdraw 250.00: balance is only 100.00
assert(condition, msg, ...) is a compact way to check assumptions; it raises an error when the condition is false:
x = [3 4 5];
try
assert(numel(x) == 2, 'Expected 2 values, got %d', numel(x));
catch err
disp(err.message)
endExpected 2 values, got 3
Built-in errors differ between programs
Errors raised by built-in functions have different messages (and identifiers) in MATLAB and Octave:
try
v = [1 2 3] + [1 2];
catch err
disp(err.message)
endoperator +: nonconformant arguments (op1 is 1x3, op2 is 1x2)
MATLAB reports Arrays have incompatible sizes for this operation. instead. Code that inspects err.message of built-in errors therefore isn't portable; base your logic on your own identifiers, or on conditions you check before calling.
Warnings
warning(msg) prints a message but doesn't stop the program. Warnings can be turned off by identifier:
warning('data:missing', 'Column %d has missing values', 3) % prints "Warning: ..."
warning('off', 'data:missing') % silence this ID
warning('on', 'data:missing')(Warnings go to the error stream and are formatted differently in MATLAB and Octave, so they aren't shown as runnable examples here.)
Cleaning up
A try/catch can make sure cleanup code runs whether or not an error happened. A common pattern is to record the error, clean up, then rethrow:
status = 'started';
try
status = 'working';
error('job:fail', 'Disk full');
catch err
status = 'cleaned up';
fprintf('Caught: %s\n', err.message);
end
fprintf('Final status: %s\n', status);Caught: Disk full
Final status: cleaned up
For resources like open files, onCleanup objects are even more robust: they run their cleanup function automatically when the function exits for any reason.
Test yourself
What happens to the remaining statements in a try block after one of them raises an error?
- They still run
- They are skipped and the catch block runs
- The program stops completely
- They run after the catch block
Which call raises an error with the identifier 'io:missing'?
error('io:missing')error('io:missing', 'File %s not found', name)warning('io:missing', 'File not found')throw('io:missing')
Why is checking err.message of built-in errors fragile?
- Messages are random
- MATLAB and Octave (and different versions) word them differently
- err.message is always empty
- It is slow