A416 of 56
0 XP
  1. Hook
  2. Predict
  3. Name it
  4. Check
  5. Explain

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 2π, 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])?

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:

ErrorUsual cause
NameErrora misspelled or undefined name
TypeErrorthe wrong kind of value, like "5" + 3
ValueErrorthe right kind but a bad value, like float("4.7k")
ZeroDivisionErrordividing by zero
IndexError, KeyErrora 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 Vs).

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
  1. Work it by hand. The right answer is 3+4+53=4
  2. Trace the loop. Printing total inside 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)
  1. Find the cause. range(1, len(xs)) starts at index 1.
  2. 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
  1. Test cases worked by hand. Two parallel pairs whose answers are known: 100 ∥ 100 is 50, and a huge resistor barely changes 1 kΩ.
  2. 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
  1. 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?

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.