Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

Lab 12: Errors, exceptions, and debugging

Objectives: LO-12.1, LO-12.2, LO-12.3, LO-12.4
Prerequisites: the Module 12 reading and Lab 11
Time: about 2 hours

In this lab you read a traceback from a script, predict which exception each of eight lines raises, write an input loop and a file reader that recover from bad input, raise errors with clear messages, and then find and fix three planted bugs with the method from the reading. Each exercise ends with a check cell that prints passed or says what is wrong.

Setup

Run the next cell first. It writes a script, stations.py, and a CSV file into scratch/lab12, and defines two helpers:

  • run_script(name) runs a script in that folder with Python, as a terminal would, and prints what it printed and its exit status.

  • typed(...) makes a stand-in for input that “types” the answers you give it, one for each call, and then raises EOFError, as input does when the input ends. The checks use it to test functions that ask for input, without a keyboard.

1. Reading a traceback

Run the next cell. It runs stations.py, which stops with a traceback.

Exercise L12.1 (LO-12.1, ★, about 10 minutes)

From the traceback above, give:

  1. t1: the exception’s name, as a string.

  2. t2: the function that raised it, and t3: the line number of the line that raised it.

  3. t4: the chain of calls, as a list of names from the first frame to the last, starting with "<module>".

  4. t5: the value in the data that caused it, as a string.

2. Which exception?

Exercise L12.2 (LO-12.1, ★, about 10 minutes)

Each of these eight expressions raises an exception. Without running them, give the name of each one’s exception as a string, in e1 to e8: for example, e1 = "TypeError".

Expression
e1int("3.5")
e2["a", "b"][2]
e3{"Harbor": 8.5}["harbor"]
e4"8.5" * 2.0
e5(8.5).append(1)
e6open("no-such-file.csv")
e7math.sqrt(-1)
e8total_rainfall + 1, where nothing has set total_rainfall

The check runs each expression and compares its exception with your answer, one at a time.

3. Recovering from bad input

Exercise L12.3 (LO-12.2, ★★, about 20 minutes)

Write ask_number(prompt, low, high, read=input), which asks for a whole number from low to high until it gets one, and returns it as an int. read is the function that reads each line: input, unless a caller passes another, as the check does with typed.

  • Convert the text with int in a try statement. For text that isn’t a whole number, print a message that shows the text with its quotes, using {text!r}, and ask again.

  • For a number outside the range, print a message that names the range, such as Type a number from 1 to 31., and ask again.

  • Catch only ValueError. When the input ends, read raises EOFError, and ask_number must let it go on to its caller, so that a program can stop politely, as convert.py does in the reading. The check also passes None as an answer, which makes int raise TypeError: a bug, which ask_number must let through too.

Hint

Follow the reading’s ask_number, with int in place of float, and read(prompt) in place of input(prompt). Check the range in the else clause, or after the try statement.

4. else and finally

Exercise L12.4 (LO-12.2, ★, about 10 minutes)

Read this function, and without running it, give:

  1. p1: the letters that describe("4") prints, in order, as a list of strings.

  2. p2: the letters that describe("x") prints, and p3: what describe("x") returns.

def describe(text):
    try:
        number = int(text)
    except ValueError:
        print("A")
        return "not a number"
    else:
        print("B")
    finally:
        print("C")
    print("D")
    return number * 2

5. Skipping bad rows

Run the next cell to see readings.csv, which the setup cell wrote. Three of its rows have a temperature that isn’t a number.

Exercise L12.5 (LO-12.2, ★★, about 15 minutes)

Write read_temperatures(path), which reads a CSV file with the columns station, date, and temp_c, and returns two lists: a (station, temperature) tuple for each row whose temp_c is a number, with the temperature as a float, and the line number of each row whose temp_c isn’t. The header is line 1, so the first row is line 2.

  • Convert temp_c in a try statement, catch ValueError, and add the good row in the else clause.

  • Don’t catch FileNotFoundError: read_temperatures can’t do anything useful about a missing file, so its caller should hear about it.

Hint

enumerate(csv.DictReader(file), start=2) numbers the rows from 2. Return the two lists as a tuple: return readings, bad_lines.

6. Raising exceptions

Exercise L12.6 (LO-12.3, ★★, about 15 minutes)

  1. Write parse_reading(line), which takes a line such as "Harbor,2026-11-02,8.5" and returns the tuple ("Harbor", "2026-11-02", 8.5). It raises ValueError with these messages:

    • for a line without exactly three fields: expected 3 fields, found 2: 'Harbor,8.5', with the number found and the line’s repr;

    • for a temperature that isn’t a number: the message float gives, so you don’t need to raise this one yourself;

    • for a temperature below -90 or above 60: temperature out of range: 85.0.

  2. Give d1: if parse_reading returned None for a bad line instead of raising, which exception would sum raise when a caller added up the temperatures, None included?

7. Finding planted bugs

Each of the next three exercises gives a function with a bug in it, and a report of what goes wrong. Find each bug with the method from the reading, then fix it in the answer cell:

  1. Reproduce the bug: run the call from the report in a new cell, and compare what you get with what you expected.

  2. Shrink the input to the smallest one that still fails.

  3. Form a hypothesis about the cause, and test it: print values with print(f"{name=}"), or use JupyterLab’s debugger, below.

  4. Fix the cause, rerun the answer cell, and confirm with the check.

Each exercise also asks you to choose the cause, as cause1, cause2, or cause3, before you fix it.

To use the debugger, turn it on with the bug button at the upper right of the notebook, whose tooltip says Enable Debugger; the debugger’s sidebar opens at the right. Click just left of a line number in a cell to set a breakpoint, a red dot, then run a cell that calls the function. The code stops at that line, and the sidebar shows the Variables there. The buttons of the Callstack panel, Next, Step In, Step Out, and Continue, run the code a line at a time. Before you run the checks, click each red dot again to remove its breakpoint, or turn the debugger off with the same bug button.

Exercise L12.7 (LO-12.4, ★★, about 10 minutes)

moving_average(values, size) should return the mean of every run of size values in a row. Report: moving_average([4, 8, 6, 2, 10], 2) should be [6.0, 7.0, 4.0, 6.0], but it is [6.0, 7.0, 4.0].

Which is the cause? Set cause1 to "A", "B", or "C", then fix the function.

  • A: Each run takes one value too few.

  • B: The loop stops one starting position too early.

  • C: The mean divides by the wrong number.

Exercise L12.8 (LO-12.4, ★★, about 10 minutes)

median(values) should return the middle value of a list, or the mean of the two middle ones. Report: after the next lines, the readings print in a different order from the one they were measured in:

readings = [8.5, 11.0, 6.5]
print(median(readings))
print(readings)

Which is the cause? Set cause2 to "A", "B", or "C", then fix the function so that it leaves its argument unchanged.

  • A: median returns the wrong value.

  • B: median changes the list that the caller passed.

  • C: print sorts a list before it prints it.

Exercise L12.9 (LO-12.4, ★★★, about 15 minutes)

total_rain(path) should add up the rain_mm column of a CSV file, skipping rows whose value isn’t a number. Report: for the file the next cell writes, it returns 0, but the total is 14.4.

Which is the cause? Set cause3 to "A", "B", or "C", then fix the function. Fix it so that a mistake of the same kind can’t hide again.

  • A: float can’t convert text with a decimal point.

  • B: The except clause hides an error that isn’t about the values.

  • C: csv.DictReader skips every row of a file that has an empty field.

Summary

In this lab you:

  • read a traceback from the bottom up: the exception, the line that raised it, and the chain of calls;

  • predicted the exceptions that common mistakes raise;

  • wrote an input loop and a file reader that recover from the errors they expect, and let the others through;

  • raised ValueError with messages that say what was wrong; and

  • found three bugs by reproducing them, shrinking the input, and testing a hypothesis, one of them hidden by an except clause that caught too much.

Next, the Module 12 practice has more exercises of each kind, in the terminal and in VS Code.