Debugging
Every program has bugs; the skill is finding them quickly. Bugs come in three flavours, and each needs a different approach:
| Kind | Symptom | First step |
|---|---|---|
| Syntax error | The file doesn't run at all; MATLAB points at a line | Read the message, look at that line and the one before |
| Run-time error | Stops with an error message partway through | Read the stack: which function, which line |
| Logic error | Runs fine but the answer is wrong | Inspect intermediate values: the debugger, or printed traces |
This lesson covers reading errors, the interactive debugger, and techniques that work even without it.
Reading the error stack
When an error escapes from deep inside your code, the message comes with a stack: the chain of calls that led to it, innermost first. Inside catch err, the same information is in err.stack, an array of structs with name and line (and file) fields:
try
load_report([3 5 0 2]);
catch err
fprintf('Error: %s\n', err.message);
for k = 1:3
fprintf(' in %s at line %d\n', err.stack(k).name, err.stack(k).line);
end
end
% --- file: load_report.m
function load_report(counts)
shares = compute_shares(counts);
fprintf('%.2f\n', shares);
end
% --- file: compute_shares.m
function s = compute_shares(counts)
s = zeros(size(counts));
for k = 1:numel(counts)
s(k) = safe_ratio(counts(k), counts(k + 1));
end
end
% --- file: safe_ratio.m
function r = safe_ratio(a, b)
if b == 0
error('report:zero', 'Division by zero (a = %g)', a);
end
r = a / b;
endError: Division by zero (a = 5)
in safe_ratio at line 3
in compute_shares at line 4
in load_report at line 2
Read it from the top: the error was raised in safe_ratio at line 3, which was called from line 4 of compute_shares, which was called from line 2 of load_report. The first frame tells you where it failed; the frames below tell you how you got there. (Here the bug is the counts(k + 1) lookup: it divides each count by the next one, which is zero for k = 2.)
In MATLAB, getReport(err) formats all of this as one text, the way the command window prints an uncaught error:
>> try, load_report([3 5 0 2]); catch err, disp(getReport(err)), end
Error using safe_ratio (line 3)
Division by zero (a = 5)
Error in compute_shares (line 4)
s(k) = safe_ratio(counts(k), counts(k + 1));
Error in load_report (line 2)
shares = compute_shares(counts);(MATLAB output. Octave 11 has no getReport; build the text yourself from err.message and err.stack, as the example above does.)
The interactive debugger
The debugger pauses your program at a chosen line so you can look at every variable, run commands, and then continue step by step. In the editor you click next to a line number to set a breakpoint; the same can be done from the command line:
| Command | Does |
|---|---|
dbstop in compute_shares at 4 |
Pause before line 4 of compute_shares.m |
dbstop in compute_shares at 4 if k > 2 |
Pause there only when the condition is true |
dbstop if error |
Pause wherever an uncaught error happens |
dbstep |
Run the current line and pause at the next |
dbstep in / dbstep out |
Go into the function called on this line / finish the current function |
dbcont |
Continue until the next breakpoint |
dbup / dbdown |
Look at the caller's (or callee's) variables |
dbstack |
Show where you are |
dbstatus, dbclear all |
List / remove breakpoints |
dbquit |
Stop debugging |
keyboard (in code) |
Pause here, as if there were a breakpoint |
A typical session in MATLAB looks like this (the K>> prompt means "paused in the debugger"; Octave shows debug>):
>> dbstop if error
>> load_report([3 5 0 2])
Error using safe_ratio (line 3)
Division by zero (a = 5)
3 error('report:zero', 'Division by zero (a = %g)', a);
K>> dbup
In workspace belonging to compute_shares
K>> k
k =
2
K>> counts(k + 1)
ans =
0
K>> dbquit
>> dbclear alldbstop if error is the most useful command of all: the program pauses at the exact failing line, with all variables still there to inspect.
Tracing without the debugger
Sometimes stepping isn't practical: a loop with thousands of iterations, code running on a server, a bug that appears only occasionally. Then print what's happening, but only when you ask for it, so you can leave the tracing in place:
x = newton_sqrt(10, true);
fprintf('result: %.6f\n', x);
x = newton_sqrt(2, false); % same code, silent
fprintf('result: %.6f\n', x);
function x = newton_sqrt(a, verbose)
x = a;
for it = 1:20
x_new = (x + a / x) / 2;
if verbose
fprintf(' it %d: x = %.6f, change = %.2e\n', it, x_new, abs(x_new - x));
end
if abs(x_new - x) < 1e-6
break
end
x = x_new;
end
x = x_new;
end it 1: x = 5.500000, change = 4.50e+00
it 2: x = 3.659091, change = 1.84e+00
it 3: x = 3.196005, change = 4.63e-01
it 4: x = 3.162456, change = 3.35e-02
it 5: x = 3.162278, change = 1.78e-04
it 6: x = 3.162278, change = 5.01e-09
result: 3.162278
result: 1.414214
Useful helpers for traces: mat2str(v) turns a small array into one line of text, size(v) and class(v) catch shape and type surprises, and dbstack called inside a function shows who called it:
outer_step();
% --- file: outer_step.m
function outer_step()
middle_step();
end
% --- file: middle_step.m
function middle_step()
inner_step([1 2; 3 4]);
end
% --- file: inner_step.m
function inner_step(M)
s = dbstack;
fprintf('inner_step was called by %s, which was called by %s\n', s(2).name, s(3).name);
fprintf('M = %s, size %s, class %s\n', mat2str(M), mat2str(size(M)), class(M));
endinner_step was called by middle_step, which was called by outer_step
M = [1 2;3 4], size [2 2], class double
Checking assumptions with assert
An assert documents an assumption and checks it. When it fails, you find out at the point where things first went wrong, not three functions later:
weights = [0.2 0.5 0.3];
assert(abs(sum(weights) - 1) < 1e-12, 'weights must sum to 1');
disp('weights OK')
scores = [80 92];
try
assert(numel(scores) == numel(weights), ...
'got %d scores for %d weights', numel(scores), numel(weights));
total = scores * weights';
catch err
disp(err.message)
endweights OK
got 2 scores for 3 weights
A gallery of common MATLAB bugs
Each of these runs without an error message but gives a surprising result, which makes them hard to spot:
% 1. Comparing floating-point numbers with ==
fprintf('0.1 + 0.2 == 0.3 -> %d\n', 0.1 + 0.2 == 0.3);
fprintf('with a tolerance -> %d\n', abs(0.1 + 0.2 - 0.3) < 1e-12);
% 2. Row + column = a matrix (implicit expansion), not an element-wise sum
a = [1 2 3];
b = [10; 20; 30]; % meant to be a row
disp(size(a + b))
% 3. Arithmetic on characters gives character codes
age = '42';
fprintf('age + 1 = %s\n', mat2str(age + 1));
fprintf('str2double(age) + 1 = %d\n', str2double(age) + 1);
% 4. Integer types saturate silently
level = uint8(250);
fprintf('uint8(250) + 10 = %d\n', level + 10);
% 5. A variable that hides a function
max = 5; % now max(...) means indexing, not the function
try
m = max([3 9 4]);
catch
disp('max([3 9 4]) failed: max is a variable here')
end
clear max % the function is back
fprintf('max([3 9 4]) = %d\n', max([3 9 4]));0.1 + 0.2 == 0.3 -> 0
with a tolerance -> 1
3 3
age + 1 = [53 51]
str2double(age) + 1 = 43
uint8(250) + 10 = 255
max([3 9 4]) failed: max is a variable here
max([3 9 4]) = 9
Avoid naming variables max, sum, i, j, length or disp; exist('name') and which name tell you whether a name is already taken (see Help & Documentation).
A debugging routine
- Reproduce the bug reliably with the smallest input you can find.
- Locate it: read the stack, or set
dbstop if error, or bisect with traces (is the value right halfway through?). - Explain it: form a hypothesis ("
k + 1runs past the end") and check it in the debugger. - Fix it, then rerun the original failing case.
- Protect the fix: turn the failing case into a test (see Unit Testing) so the bug can't silently return.
Learn more: Error Handling for try/catch and error identifiers, Input Validation to catch bad inputs at the door.
Test yourself
Which command makes MATLAB pause at the exact line where an uncaught error occurs?
dbstepdbstop if errordbcontkeyboard off
In err.stack, which element describes where the error was actually raised?
- The first,
err.stack(1) - The last,
err.stack(end) - It depends on the program
- None; the stack only lists callers
Why does '42' + 1 give [53 51] rather than 43?
- A rounding error
- Characters are added as their character codes
- Strings are added digit by digit
- It is a bug in MATLAB