TExcelTAD
Home › MATLAB / Octave › Error Handling

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:

matlab · try it yourself
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
end
12 -> 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:

matlab · try it yourself
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));
end
result: 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:

matlab · try it yourself
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:

matlab · try it yourself
x = [3 4 5];
try
    assert(numel(x) == 2, 'Expected 2 values, got %d', numel(x));
catch err
    disp(err.message)
end
Expected 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:

matlab · try it yourself
try
    v = [1 2 3] + [1 2];
catch err
    disp(err.message)
end
operator +: 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:

matlab
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:

matlab · try it yourself
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?

  1. They still run
  2. They are skipped and the catch block runs
  3. The program stops completely
  4. They run after the catch block

Which call raises an error with the identifier 'io:missing'?

  1. error('io:missing')
  2. error('io:missing', 'File %s not found', name)
  3. warning('io:missing', 'File not found')
  4. throw('io:missing')

Why is checking err.message of built-in errors fragile?

  1. Messages are random
  2. MATLAB and Octave (and different versions) word them differently
  3. err.message is always empty
  4. It is slow