Skip to content
Tutorials Center
My learning

Topics

Lesson 20 of 45 ยท Programming

Errors, Warnings and Debugging

Raise and handle errors in MATLAB and Octave with error, warning, try/catch, MException and assert, use breakpoints and dbstop, and decode common error messages.

Every program meets bad input, missing files and plain mistakes. MATLAB and Octave give you two sets of tools: ways to signal and handle problems in code (error, warning, try/catch, assert) and ways to find mistakes interactively (breakpoints and the debugger). Using both well turns a cryptic red message into a five-minute fix.

The real MATLAB/Octave code in this lesson is read-only. Python's try/except and assert are runnable stand-ins that behave in a very similar way.

Four levels of trouble

Message disp or fprintf for plain information.
Warning warning keeps the program running.
Error error stops the current call stack.
Debug Breakpoints let you pause and look inside.

Pick the mildest level that is still honest.

1 / 2

Raising errors with error

error stops execution and prints a message. It accepts sprintf-style formatting, and an optional identifier of the form Component:mnemonic that code can test for later.

MATLAB
function r = safe_sqrt(x)
    if x < 0
        error('Mathlib:negativeInput', ...
              'safe_sqrt needs x >= 0, but got %g.', x);
    end
    r = sqrt(x);
end

safe_sqrt(-4)
% Error using safe_sqrt
% safe_sqrt needs x >= 0, but got -4.

Write messages that say what was expected and what was received. An identifier is optional but useful, because callers can react to one specific failure without matching message text. Note that the identifier must contain a colon and no whitespace, otherwise MATLAB treats the first argument as the message itself.

Warnings

warning prints a message and carries on. Use it for suspicious but survivable situations, such as a deprecated option or a value that was clipped.

MATLAB
warning('Mathlib:clipped', 'Value %g clipped to 1.', 1.7);

warning('off', 'Mathlib:clipped');   % silence one kind
warning('on',  'Mathlib:clipped');   % bring it back

[msg, id] = lastwarn;                % the most recent warning

Turning warnings off globally with warning('off', 'all') hides real problems; prefer switching off a single identifier around the one statement that triggers it.

try and catch

Wrap code that may fail in try and handle the failure in catch. The caught object tells you what happened.

MATLAB
try
    A = [1 2 3] + [1 2];
catch err
    disp(err.identifier);   % MATLAB: MATLAB:sizeDimensionsMustMatch
    disp(err.message);      % Arrays have incompatible sizes for this operation.
end

The variable (here err) is an MException object in MATLAB. In Octave the same fields message, identifier and stack exist on the caught error. Useful tools:

  • err.message, err.identifier, err.stack describe the problem and where it happened.
  • rethrow(err) raises the same error again after you log it.
  • MException('Pkg:id', 'Text %d', 5) builds an error object and throw(ME) raises it.
  • getReport(err) (MATLAB) returns a formatted multi-line description.

There is no finally keyword in MATLAB. To guarantee cleanup such as closing a file, create c = onCleanup(@() fclose(fid)); and the handle runs when c goes out of scope. Octave offers unwind_protect ... unwind_protect_cleanup ... end_unwind_protect for the same purpose.

Python try/except as a stand-in for try/catch

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The structure is the same: guarded block, error object with a message and identifier, and a handler. The differences are the names and the existence of finally.

Checking assumptions with assert

assert raises an error when a condition is false, which makes it ideal for stating what must be true.

MATLAB
assert(all(x > 0), 'All inputs must be positive.');
assert(isnumeric(n) && n == round(n), ...
       'Mathlib:notInteger', 'n must be an integer, got %g.', n);

% Test style: compare with a tolerance
assert(abs(result - 3.1416) < 1e-4);

In Octave, assert(observed, expected, tol) compares values directly, which is why many Octave test blocks use it. Both systems also offer validateattributes (type and range checks) and inputParser (named options), covered by their documentation, for functions with richer inputs. Checking inputs early, as discussed in Scripts and Functions, gives clear messages near the cause instead of strange ones deep inside.

Python assert in a small test

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Reading common error messages

Most errors fall into a few families. The wording differs slightly between MATLAB and Octave, but the cause is the same.

Cause MATLAB message (short form) Octave message
Misspelled or missing name Unrecognized function or variable 'speed'. 'speed' undefined
Adding arrays of different sizes Arrays have incompatible sizes for this operation. operator +: nonconformant arguments (op1 is 1x3, op2 is 1x2)
Wrong * shapes Incorrect dimensions for matrix multiplication... operator *: nonconformant arguments (op1 is 2x3, op2 is 2x3)
Index past the end Index exceeds the number of array elements. index (5,_): out of bound 3
Index zero or fractional Index in position 1 is invalid. Array indices must be positive integers or logical values. index (0): out of bound; value 0 out of bound 3
Too many arguments Too many input arguments. Invalid call to f

How to approach them:

  1. Read the first line and the line number; the last frame in the stack is usually where to look.
  2. Check sizes with size(A) for every operand. Dimension errors almost always come from a row/column mix-up or from using * where you meant .* (see Arithmetic: Matrix vs Element-wise).
  3. Check names with which name and exist('name'). A typo or a script that never ran is the usual culprit for "undefined".
  4. Check indexing: MATLAB counts from 1 (see Indexing and Slicing), so A(0) is always an error.

Debugging with breakpoints

When the message is not enough, pause the program and look around.

  • Click the dash beside a line number in the editor to set a breakpoint; or type dbstop in myfile at 12.
  • dbstop if error pauses at the exact line where an uncaught error happens, with all variables still alive. This is the single most useful debugging command.
  • At the K>> prompt (Octave: debug>), the workspace is that of the paused function. Print variables, run expressions, and check sizes.
  • dbstep runs one line, dbstep in steps into a called function, dbcont continues, dbquit leaves debug mode.
  • dbstack shows who called whom; dbclear all removes breakpoints.
  • Put keyboard in code to drop into a prompt at that spot, and return or dbcont to resume.
MATLAB
dbstop if error
result = mean_positive([1 -2 3]);   % pauses inside, at the failing line
K>> x                               % inspect
K>> dbstack
K>> dbquit

Cheap tools help too: leave off the semicolon to print a value, and use disp(size(A)) or whos to confirm shapes. Fix one error at a time and rerun, because later errors may disappear once the first is fixed.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which call raises an error with an identifier and a formatted message?

    When the first argument looks like Component:mnemonic and more arguments follow, it is the identifier and the next argument is the format string. warning does not stop the program.
  2. 2. What is the difference between warning and error?

    A warning is informational and execution continues. An error aborts unless a surrounding try/catch handles it.
  3. 3. You see: Arrays have incompatible sizes for this operation. What is the best first step?

    This message means two operands cannot be combined element by element or through implicit expansion. Printing their sizes usually shows a row-versus-column mix-up.
  4. 4. What does dbstop if error do?

    The program stops at the failing line with its variables intact, so you can inspect values at the K>> prompt.

Summary

  • error stops execution; add an identifier (Pkg:name) and sprintf-style text. warning informs and continues.
  • try/catch err catches errors; use err.message, err.identifier, err.stack, rethrow and MException.
  • MATLAB has no finally: use onCleanup (Octave: unwind_protect).
  • assert states what must be true and fails loudly otherwise.
  • Common messages (undefined name, incompatible sizes, index out of range) point to typos, shape mix-ups and 1-based indexing.
  • dbstop if error, breakpoints, dbstep, dbcont and dbstack let you inspect a paused program.

Next, make your code fast and short with Vectorization.