A4 · Lesson 16 · Errors, exceptions and testing
Code that fails loudly is code you can trust
The worst bug in engineering code isn't the one that crashes. It's the one that quietly returns a plausible wrong number: a filter designed with a corner off by , a resistance computed as negative and used anyway. Good code does the opposite: it refuses nonsense inputs with a clear message, handles the failures it expects, and comes with tests that prove it gives the right answers on cases you can check by hand.
Predict
What happens when Python runs x = [1, 2, 3] and then print(x[3])?
It stops with IndexError: list index out of range. Indexes run from 0 to 2, so there's no x[3]. Python doesn't guess or quietly return something; it raises an exception, which stops the program unless something catches it, and the traceback tells you the line.
Name it
Reading a traceback
When an exception isn't caught, Python prints a traceback: the chain of calls that led to the error, ending with the line that failed and the error's type and message. Read it from the bottom up. The common ones:
| Error | Usual cause |
|---|---|
NameError | a misspelled or undefined name |
TypeError | the wrong kind of value, like "5" + 3 |
ValueError | the right kind but a bad value, like float("4.7k") |
ZeroDivisionError | dividing by zero |
IndexError, KeyError | a missing list position or dictionary key |
Raising errors yourself
If a function gets an input that makes no physical sense, stop with a clear message instead of returning nonsense:
def current(V, R):
if R <= 0:
raise ValueError(f"R must be positive, got {R}")
return V / R
Catching errors you expect
try and except handle a failure you can anticipate, like bad text from a user or a file:
def safe_float(text):
try:
return float(text)
except ValueError:
return None
Catch only the specific error you expect. A bare except: also hides the bugs you didn't expect.
Tests
A test runs code on cases with known answers and checks the result with assert:
assert abs(parallel(100, 100) - 50) < 1e-12
assert abs(divider(12, 10e3, 10e3) - 6) < 1e-12
Good tests check:
- cases you can do by hand (two equal resistors in parallel give half);
- edge cases (zero, one item, the largest input);
- properties that must always hold (the parallel value is below both resistors; a divider's output is between 0 and ).
The labs in this course work the same way: a hidden set of asserts.
Debugging
When a test fails: shrink the input to the smallest case that still fails, print the intermediate values, and compare each against what you'd get by hand. The first place they differ is the bug.
Worked example
A function meant to average the absolute values of a list returns the wrong answer for [3, -4, 5]. Find the bug.
Show the solution
- Work it by hand. The right answer is
- Trace the loop. Printing
totalinside the loop of the function below shows 4 then 9: the 3 is never added.
def mean_abs(xs):
total = 0
for k in range(1, len(xs)):
total += abs(xs[k])
return total / len(xs)
- Find the cause.
range(1, len(xs))starts at index 1. - Fix it. Use
range(len(xs)), or better,for x in xs:.
Answer the loop starts at index 1 and skips the first item; loop over range(len(xs)), or better, for x in xs:.
Worked example
Write tests for parallel(R1, R2).
Show the solution
- Test cases worked by hand. Two parallel pairs whose answers are known: 100 ∥ 100 is 50, and a huge resistor barely changes 1 kΩ.
- Test properties over several cases. The result is smaller than either resistor, and the order of the arguments doesn't matter.
assert abs(parallel(100, 100) - 50) < 1e-12 # by hand
assert abs(parallel(1e3, 1e12) - 1e3) < 1e-6 # a huge resistor barely matters
for a, b in [(1, 2), (470, 1e3), (1e6, 3.3)]:
p = parallel(a, b)
assert p < min(a, b) # a property
assert abs(parallel(b, a) - p) < 1e-12 * p # order doesn't matter
- Why properties help. Checking properties over several cases catches bugs that one hand-worked example might miss.
Answer two asserts worked by hand, plus a loop that checks two properties of the result over several pairs.
Check
Write current(V, R) that returns V / R, but raises a ValueError if R is zero or negative. Then set I = current(V, R) for V = 5 and R = 100.
Python 3.14 with numpy and matplotlib, running in your browser. Tab indents; press Esc and then Tab to move on.
Check
Write safe_float(text) that returns float(text), or None if the text isn't a number. Then set vals to safe_float applied to each string in the starter's list.
Python 3.14 with numpy and matplotlib, running in your browser. Tab indents; press Esc and then Tab to move on.
Check
The starter's mean_abs has a bug. Fix it so it returns the mean of the absolute values, then set m = mean_abs(xs).
Python 3.14 with numpy and matplotlib, running in your browser. Tab indents; press Esc and then Tab to move on.
Check
Look up each name in the parts dictionary. Set values to the list of their values, using 0 for any name that isn't in it, without letting a KeyError stop the program.
Python 3.14 with numpy and matplotlib, running in your browser. Tab indents; press Esc and then Tab to move on.
Check
Write passes(f) that tests a candidate parallel(R1, R2) function and returns True only if it gets parallel resistors right. It must accept the correct formula and reject the three broken versions in the starter. Use math.isclose for the comparisons.
Python 3.14 with numpy and matplotlib, running in your browser. Tab indents; press Esc and then Tab to move on.
Check
What does this print?
try:
x = int("4.7")
print("A")
except ValueError:
print("B")Explain why
Why is it better for a function to raise an error on a negative resistance than to return a number anyway?
A negative resistance means something upstream has gone wrong: a typo, a sign error or a bad measurement. If the function returns a number anyway, the mistake flows silently into later calculations and shows up, if at all, as a wrong result far from its cause. Raising an error stops the program right where the bad value appears, with a message that says what was wrong, so the bug is found immediately.
Practice
Keep practicing
6 kinds of problem on this topic, dealt one at a time with new numbers every time, for as long as you like.