---
title: Errors, exceptions and testing
heading: Code that fails loudly is code you can trust
eyebrow: A4 · Lesson 16 · Errors, exceptions and testing
xp: 40
---

::: hook
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\pi$, 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 prints 3
- [ ] It prints `None`
- [x] It stops with an `IndexError`
- [ ] It prints 0

::: reveal
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.
:::
:::

::: nameit
## 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 $V_s$).

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

::: example
## A function meant to average the absolute values of a list returns the wrong answer for `[3, -4, 5]`. Find the bug.

::: solution
1. **Work it by hand.** The right answer is
   $$\frac{3 + 4 + 5}{3} = 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)
```

3. **Find the cause.** `range(1, len(xs))` starts at index 1.
4. **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:`.
:::
:::

::: example
## Write tests for `parallel(R1, R2)`.

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

3. **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
kind: python
given: V = 5 | 12; R = 100 | 470

## 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` = {V} and `R` = {R}.

```python starter
def current(V, R):
    return V / R

I = current(V, R)
print(I)
```

```python solution
def current(V, R):
    if R <= 0:
        raise ValueError(f"R must be positive, got {R}")
    return V / R

I = current(V, R)
print(I)
```

```python tests
import math
assert math.isclose(I, V / R), "I should be V / R."
try:
    current(5, -10)
    raised = False
except ValueError:
    raised = True
assert raised, "current(5, -10) should raise a ValueError: a negative resistance makes no sense."
try:
    current(5, 0)
    raised = False
except ValueError:
    raised = True
except ZeroDivisionError:
    raised = False
assert raised, "current(5, 0) should raise a ValueError with a clear message, before Python divides by zero."
```

::: right
Right. A clear `ValueError` at the boundary beats a confusing failure, or a wrong number, later on.
:::
:::

::: check
kind: python
given: k = 0..3 int

## 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 starter
def safe_float(text):
    return float(text)

texts = [["3.3", "5", "abc", "12"], ["4.7k", "1e-3", "x"], ["", "2.5", "-1"], ["0.5", "five", "7"]][k]
vals = []
print(vals)
```

```python solution
def safe_float(text):
    try:
        return float(text)
    except ValueError:
        return None

texts = [["3.3", "5", "abc", "12"], ["4.7k", "1e-3", "x"], ["", "2.5", "-1"], ["0.5", "five", "7"]][k]
vals = [safe_float(t) for t in texts]
print(vals)
```

```python tests
want = [[3.3, 5.0, None, 12.0], [None, 0.001, None], [None, 2.5, -1.0], [0.5, None, 7.0]][k]
assert vals == want, f"vals should be {want}. Wrap float(text) in try/except ValueError and return None on failure."
```

::: right
Right. The exception is expected here, so catching it is the right call. Catch `ValueError` only, so other bugs still show.
:::
:::

::: check
kind: python
given: k = 0..3 int

## 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 starter
def mean_abs(xs):
    total = 0
    for k in range(1, len(xs)):
        total += abs(xs[k])
    return total / len(xs)

xs = [[3, -4, 5], [-2, -2, 2, 2], [10, -1], [-6, 1, -1, 2, 2]][k]
m = mean_abs(xs)
print(m)
```

```python solution
def mean_abs(xs):
    total = 0
    for x in xs:
        total += abs(x)
    return total / len(xs)

xs = [[3, -4, 5], [-2, -2, 2, 2], [10, -1], [-6, 1, -1, 2, 2]][k]
m = mean_abs(xs)
print(m)
```

```python tests
assert abs(mean_abs([3, -4, 5]) - 4) < 1e-12, "mean_abs([3, -4, 5]) should be 4. Check which items the loop visits."
assert abs(mean_abs([-7]) - 7) < 1e-12, "mean_abs([-7]) should be 7."
```

::: right
Right. The loop skipped the first item. `for x in xs` can't make that mistake.
:::
:::

::: check
kind: python
given: k = 0..2 int

## 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 starter
parts = {"R1": 4700, "R2": 1000, "C1": 1e-7}
names = [["R1", "C1", "Q1"], ["R2", "R9", "C1"], ["L1", "R1"]][k]
values = [parts[n] for n in names]
print(values)
```

```python solution
parts = {"R1": 4700, "R2": 1000, "C1": 1e-7}
names = [["R1", "C1", "Q1"], ["R2", "R9", "C1"], ["L1", "R1"]][k]
values = [parts.get(n, 0) for n in names]
print(values)
```

```python tests
assert values == [[4700, 1e-7, 0], [1000, 0, 1e-7], [0, 4700]][k], "Use parts.get(name, 0), which returns 0 for a missing key."
```

::: right
Right. `get` with a default avoids the exception altogether when a missing key is normal.
:::
:::

::: check
kind: python

## 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 starter
import math

def good(R1, R2): return R1 * R2 / (R1 + R2)
def bad_sum(R1, R2): return R1 + R2
def bad_parens(R1, R2): return R1 * R2 / R1 + R2
def bad_half(R1, R2): return R1 / 2

def passes(f):
    return f(1000, 1000) == 500

results = [passes(g) for g in (good, bad_sum, bad_parens, bad_half)]
print(results)
```

```python solution
import math

def good(R1, R2): return R1 * R2 / (R1 + R2)
def bad_sum(R1, R2): return R1 + R2
def bad_parens(R1, R2): return R1 * R2 / R1 + R2
def bad_half(R1, R2): return R1 / 2

def passes(f):
    cases = [(1000, 1000, 500), (1000, 3000, 750), (2200, 4700, 2200 * 4700 / 6900), (10, 1e6, 10 * 1e6 / (1e6 + 10))]
    return all(math.isclose(f(a, b), want, rel_tol=1e-9) for a, b, want in cases)

results = [passes(g) for g in (good, bad_sum, bad_parens, bad_half)]
print(results)
```

```python tests
assert results == [True, False, False, False], f"passes should give [True, False, False, False], not {results}. A test with two equal resistors can't tell R1/2 from the real formula: try unequal ones too."
def bad_swap(R1, R2): return R2 * R2 / (R1 + R2)
assert passes(bad_swap) is False, "Your tests should also catch a version that uses R2 twice. Check unequal values."
```

::: right
Right. Equal resistors are the case every wrong formula is most likely to get right by accident, so good tests include unequal values with known answers. A test is only as good as the bugs it catches.
:::
:::

::: check
kind: choice

## What does this print?

```python
try:
    x = int("4.7")
    print("A")
except ValueError:
    print("B")
```

- [x] `B`
- [ ] `A`
- [ ] `A`, then `B`
- [ ] `4`

::: right
Right. `int` won't parse text with a decimal point, so `int("4.7")` raises a `ValueError` before `print("A")` runs, and the `except` branch prints `B`. `int(float("4.7"))` would give 4.
:::

::: misses
- [2] `int("4.7")` fails: `int` only reads whole-number text. The error skips the rest of the `try` block.
- [3] When the error happens, the rest of the `try` block is skipped, so `A` never prints.
- [4] `int` of the number 4.7 would be 4, but `int` of the text `"4.7"` raises an error.
:::
:::

::: explain
## Why is it better for a function to raise an error on a negative resistance than to return a number anyway?

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

::: check
kind: python
given: k = 0..2 int

## Write `to_int(text)` returning `int(text)`, or −1 if that fails. Set `n = to_int(s)` for the starter's string.

```python starter
def to_int(text):
    return int(text)

s = ["42", "4.2", "x7"][k]
n = None
print(n)
```

```python solution
def to_int(text):
    try:
        return int(text)
    except ValueError:
        return -1

s = ["42", "4.2", "x7"][k]
n = to_int(s)
print(n)
```

```python tests
assert to_int("42") == 42 and to_int("4.2") == -1 and to_int("x7") == -1, "Catch the ValueError and return −1."
assert n == [42, -1, -1][k], "n doesn't match."
```
:::

::: check
kind: python
given: tau = 1e-6 | 1e-5 | 1e-4 | 0.001 | 0.01

## Write `rc_tau(R, C)` returning `R * C`, raising `ValueError` if either is negative. Set `t = rc_tau(1000, tau / 1000)`.

```python starter
def rc_tau(R, C):
    return R * C

t = 0
print(t)
```

```python solution
def rc_tau(R, C):
    if R < 0 or C < 0:
        raise ValueError("R and C must not be negative")
    return R * C

t = rc_tau(1000, tau / 1000)
print(t)
```

```python tests
import math
assert math.isclose(t, tau), "t should be R·C."
try:
    rc_tau(-1, 1e-6)
    ok = False
except ValueError:
    ok = True
assert ok, "A negative R should raise ValueError."
```
:::
:::
