Objectives: LO-12.1, LO-12.2, LO-12.3, LO-12.4
Prerequisites: Module 5 and
Module 11
Time: about 5.5 hours: 2 for this reading, 2 for Lab 12, and 1.5 for the
practice
Every program meets input it didn’t expect, files that aren’t there, and mistakes of its own. This module teaches you to read the report Python prints when something goes wrong, to handle the errors a program can recover from, to stop with a clear message when it can’t, and to find a bug by a method instead of by guessing. Until now, a program that met bad input had to check every character before converting it; after this module, it can try the conversion and recover if it fails.
Exceptions and tracebacks¶
When Python can’t carry out an instruction, such as dividing by zero or opening a file that isn’t there, it raises an exception: an object that says what went wrong. Unless some part of the program handles the exception, the program stops and prints a traceback, a report of where the exception happened and how the program got there.
This script, averages.py, prints each station’s average temperature. The second station has no
readings yet:
"""Print each station's average temperature."""
def average(values):
return sum(values) / len(values)
def report(readings):
for station, temps in readings.items():
print(f"{station}: {average(temps):.1f} °C")
def main():
readings = {"Harbor": [8.5, 11.0, 6.5], "Hilltop": []}
report(readings)
main()Run it in a terminal, in a folder m12 inside py101:
python averages.pyHarbor: 8.7 °C
Traceback (most recent call last):
File ".../py101/m12/averages.py", line 18, in <module>
main()
~~~~^^
File ".../py101/m12/averages.py", line 15, in main
report(readings)
~~~~~~^^^^^^^^^^
File ".../py101/m12/averages.py", line 10, in report
print(f"{station}: {average(temps):.1f} °C")
~~~~~~~^^^^^^^
File ".../py101/m12/averages.py", line 5, in average
return sum(values) / len(values)
~~~~~~~~~~~~^~~~~~~~~~~~~
ZeroDivisionError: division by zeroEach File line gives the script’s full path; here, the folders before py101 are left out. The
output is from Python 3.15. Older versions, such as Python 3.12, mark fewer of the lines with
~ and ^, and newer ones print the traceback in color in a terminal.
Reading a traceback¶
Read a traceback from the bottom up:
The last line names the exception and gives its message:
ZeroDivisionError: division by zero. Start here: the name says what kind of thing went wrong.The last frame, the
Fileline just above it with its line of code, says where the exception was raised: line 5 ofaverages.py, in the functionaverage. Under the line,^marks the operation that failed, the division, and~marks its parts.The frames above it are the chain of calls that led there, oldest first, as the heading “most recent call last” says. Each frame is a call that hadn’t returned yet: the script’s own code (
<module>) calledmainon line 18,maincalledreporton line 15, andreportcalledaverageon line 10.
The traceback says where Python noticed the problem, which isn’t always where the mistake is.
average divided by zero because report passed it an empty list, and report got that list
from main. Whether the fix belongs in average (refuse an empty list with a clear message),
in report (skip stations with no readings), or in the data is a decision about what the
program should do. The traceback gives you the chain of calls to follow; it doesn’t decide.
Tracebacks in a notebook¶
JupyterLab shows the same information in its own layout. Each frame starts with the cell it came
from, as Cell In[2], the number in the brackets beside the cell, and an arrow marks the line:
---------------------------------------------------------------------------
ZeroDivisionError Traceback (most recent call last)
Cell In[2], line 2
1 temps = []
----> 2 print(average(temps))
Cell In[1], line 2, in average(values)
1 def average(values):
----> 2 return sum(values) / len(values)
ZeroDivisionError: division by zeroCommon exceptions¶
The exception’s name is the first clue. These are the ones you’ll meet most:
| Exception | What it means | Example | Its message |
|---|---|---|---|
SyntaxError | The code isn’t valid Python, so none of it runs | print("hi" | '(' was never closed |
NameError | A name has no value: often a typo, or a variable used before it is set | totl + 1 | name 'totl' is not defined |
TypeError | An operation got a value of the wrong type | "3" + 4 | can only concatenate str (not "int") to str |
ValueError | The type is right, but the value isn’t | int("ten") | invalid literal for int() with base 10: 'ten' |
IndexError | A position past the end of a list or string | [1, 2][5] | list index out of range |
KeyError | A key that isn’t in the dictionary | {"a": 1}["b"] | 'b' |
AttributeError | A method or attribute that the type doesn’t have | "abc".push("d") | 'str' object has no attribute 'push' |
ZeroDivisionError | Division or % by zero | 7 / 0 | division by zero |
FileNotFoundError | No file at that path | open("missing.txt") | [Errno 2] No such file or directory: 'missing.txt' |
RecursionError | Too many calls waiting at once, usually a missing base case | Module 11’s depth(data) bug | maximum recursion depth exceeded |
A SyntaxError is different from the rest: Python finds it while reading the file, before any of
the program runs, and its message points at the place it stopped making sense, which may be after
the real mistake, such as a missing ) on an earlier line.
Handling exceptions¶
try and except¶
A try statement runs a block of code, and if a line in it raises an exception that an except
clause names, Python skips the rest of the block and runs that clause instead. This function asks
until the user types a number:
def ask_number(prompt):
"""Ask until the user types a number, and return it as a float."""
while True:
text = input(prompt)
try:
return float(text)
except ValueError:
print(f"{text!r} isn't a number. Try again.")If float(text) succeeds, return ends the function. If it raises ValueError, the except
clause prints a message and the loop asks again. An exception that the except clause doesn’t
name, such as a TypeError, isn’t handled: it goes on to the code that called ask_number, and
then to the code that called that, and if nothing handles it, the program stops with a
traceback.
Compare this with the input-validation loops of Modules 4 and 6, which checked each character
before calling int. Asking float to try, and recovering when it can’t, accepts everything
float accepts, -3.5, 1e3, and 7 included, without a check of your own that might
disagree with it. It accepts nan and inf too, so a program that needs a real measurement
should also check the number’s range.
To use the exception’s message, name it with as:
try:
int("7.5")
except ValueError as error:
print("Not a whole number:", error)Not a whole number: invalid literal for int() with base 10: '7.5'To handle several kinds of exception the same way, list them in parentheses:
except (ValueError, KeyError):.
Catch only what you can recover from¶
An except clause should name only the exceptions the code can do something sensible about. A
clause that names Exception, or a bare except: that names nothing, catches almost everything,
your own bugs included. Suppose ask_number had a typo:
def ask_number(prompt):
"""Ask until the user types a number, and return it as a float."""
while True:
text = input(prompt)
try:
return flaot(text)
except Exception:
print(f"{text!r} isn't a number. Try again.")flaot raises NameError, which except Exception catches, so the function answers '21' isn't a number. Try again. to every number, forever, and never shows the traceback that would have
pointed at the typo. With except ValueError, the first number typed stops the program with
NameError: name 'flaot' is not defined, and the bug takes a minute to fix.
Two habits keep an except clause honest:
Name the exception you expect. The Python tutorial calls it good practice to be as specific as possible.
Keep the
tryblock short: only the lines that can raise the exception you expect. AValueErrorfrom some other line in a long block would get the wrong message.
Ctrl+C and the end of input¶
Two keys stop a program that is waiting for input. Ctrl+C raises KeyboardInterrupt, and
ending the input, with Ctrl+D on macOS and Linux or Ctrl+Z then Enter on Windows,
makes input raise EOFError (EOF stands for “end of file”). Either one stops ask_number with
a traceback that ends like this:
File ".../py101/m12/convert.py", line 7, in ask_number
text = input(prompt)
EOFError: EOF when reading a lineThe user meant to stop, so the program should stop politely. Handle both exceptions once, at the
top of the program, in main. This script, convert.py, converts temperatures until the user
stops it:
"""Convert temperatures from Celsius to Fahrenheit until the user stops."""
def ask_number(prompt):
"""Ask until the user types a number, and return it as a float."""
while True:
text = input(prompt)
try:
return float(text)
except ValueError:
print(f"{text!r} isn't a number. Try again.")
def main():
try:
while True:
celsius = ask_number("Celsius: ")
print(f"{celsius} °C is {celsius * 9 / 5 + 32:.1f} °F")
except (KeyboardInterrupt, EOFError):
print()
print("Goodbye.")
if __name__ == "__main__":
main()A session that ends with Ctrl+D:
Celsius: 21
21.0 °C is 69.8 °F
Celsius: warm
'warm' isn't a number. Try again.
Celsius:
'' isn't a number. Try again.
Celsius: -3.5
-3.5 °C is 25.7 °F
Celsius:
Goodbye.The print() before Goodbye. ends the line the prompt was on. KeyboardInterrupt isn’t a
kind of Exception, so except Exception doesn’t catch it. The Python documentation says this
is on purpose: so that code catching Exception doesn’t accidentally stop the user from
interrupting a program.
else and finally¶
A try statement can have two more clauses. else runs only when the try block raised
nothing, and finally runs every time, whatever happened:
for text in ["12", "twelve"]:
try:
value = int(text)
except ValueError:
print(f"{text!r}: not a whole number")
else:
print(f"{text!r}: doubled is {value * 2}")
finally:
print(f"{text!r}: done")'12': doubled is 24
'12': done
'twelve': not a whole number
'twelve': doneCode in else could go at the end of the try block instead, but then a ValueError from that
code would get the except clause’s message too. Keeping it in else keeps the try block to
the one line that is expected to fail. finally is for cleanup that must happen even when the
block returns or raises: it runs before the function returns, and before an unhandled exception
goes on to the caller. A with statement already closes files, so you’ll need finally less
often than its description suggests.
Handle each exception where you can do something about it¶
Module 11 promised a kinder way to report a JSON file that is broken. This function loads a settings file, and returns no settings if the file isn’t there, which is normal the first time a program runs:
import json
from pathlib import Path
def load_settings(path):
"""Return the settings saved as JSON at path, or {} if there is no such file."""
try:
with open(path, encoding="utf-8") as file:
return json.load(file)
except FileNotFoundError:
return {}A file that is there but isn’t valid JSON is different: load_settings can’t know whether its
caller would rather stop or carry on with the defaults, so it lets json.JSONDecodeError go on to
the caller. The caller decides, and says exactly what is wrong:
Path("settings.json").write_text('{"units": "metric" "station": "Harbor"}', encoding="utf-8")
try:
settings = load_settings("settings.json")
except json.JSONDecodeError as error:
print(f"settings.json isn't valid JSON: {error.msg}, line {error.lineno}, column {error.colno}")
print("Using the default settings.")
settings = {}
print(load_settings("no-such-file.json"))settings.json isn't valid JSON: Expecting ',' delimiter, line 1, column 20
Using the default settings.
{}JSONDecodeError keeps its message and position as msg, lineno, and colno. It is a kind of
ValueError, so except ValueError would catch it too.
Raising exceptions¶
raise, with a message¶
Your own functions can raise exceptions, with the raise statement. Raise one when a function
can’t do its job, and say in the message what was wrong and with which value. This function
parses one line of a readings file:
def parse_reading(line):
"""Return the date and temperature in a line such as "2026-11-02,8.5"."""
fields = line.split(",")
if len(fields) != 2:
raise ValueError(f"expected 2 fields, found {len(fields)}: {line!r}")
date, text = fields
temperature = float(text)
if not -90 <= temperature <= 60:
raise ValueError(f"temperature out of range: {temperature}")
return date, temperatureraise stops the function at once, as return does, but instead of a value it sends the
exception to the caller. float(text) raises its own ValueError for text that isn’t a number,
with a message that already shows the text, so all three problems reach the caller as
ValueError, and one except clause handles them all:
lines = [
"2026-11-02,8.5",
"2026-11-03",
"2026-11-04,warm",
"2026-11-05,85",
"2026-11-06,6.5",
]
for number, line in enumerate(lines, start=1):
try:
date, temperature = parse_reading(line)
except ValueError as error:
print(f"line {number}: {error}")
else:
print(f"line {number}: {date} {temperature} °C")line 1: 2026-11-02 8.5 °C
line 2: expected 2 fields, found 1: '2026-11-03'
line 3: could not convert string to float: 'warm'
line 4: temperature out of range: 85.0
line 5: 2026-11-06 6.5 °C{line!r} shows the value’s repr, with its quotes, so an empty string or a stray space is
visible in the message. Choose the exception type a caller would expect: ValueError for a bad
value, TypeError for a value of the wrong type. Exception types of your own need classes,
which Module 14 introduces; section 8.6 of the Python tutorial shows how to define them.
Raise, or return a special value?¶
A function that can’t give an answer can raise an exception, or return a special value such as
None, -1, or "". Python does both. A dictionary’s d[key] raises KeyError for a missing
key, and d.get(key) returns None; a string’s text.index(part) raises ValueError when
part isn’t there, and text.find(part) returns -1.
A special value is a good answer when “not found” is a normal result that every caller expects
and checks, such as looking up a word that may not be in a dictionary. A special value that a
caller forgets to check, though, travels on and fails somewhere else. If parse_reading returned
None for a bad line, the error would appear later, far from its cause:
def temperature_or_none(line):
"""Return the temperature in line, or None if the line is bad."""
try:
return parse_reading(line)[1]
except ValueError:
return None
temperatures = [temperature_or_none(line) for line in lines]
print(temperatures)
print(sum(temperatures))[8.5, None, None, None, 6.5]
TypeError: unsupported operand type(s) for +: 'float' and 'NoneType'The TypeError’s traceback points at sum, which did nothing wrong. Raise an exception when a
function can’t do its job and its caller shouldn’t carry on as if it had; return a special value
only when the “no answer” case is normal and the caller can’t easily forget it.
assert is for bugs, not for input¶
The labs’ checks use assert, which raises AssertionError when its condition is false. Use
assert in your own code only for things that can’t be false unless the program has a bug, never
to check input: running Python with the -O option (“optimize”) removes every assert
statement, and a user’s bad input would then pass unchecked. Check input with if and raise.
Finding bugs with a method¶
A program can run without an error and still give the wrong answer. This function should return the median of a list, the middle value once it’s sorted, or the mean of the two middle values when there is an even number of them:
def median(values):
"""Return the middle value of values, or the mean of the two middle ones."""
ordered = sorted(values)
middle = len(ordered) // 2
if len(ordered) % 2 == 0:
return (ordered[middle] + ordered[middle + 1]) / 2
return ordered[middle]
print(median([8.5, 11.0, 6.5, 7.0]))9.75Sorted, the temperatures are 6.5, 7.0, 8.5, and 11.0, so the median is the mean of 7.0 and 8.5, 7.75. Changing lines until the answer looks right can hide a bug instead of fixing it. A method finds the cause, the same way every time:
Reproduce the bug. Find an input that shows the bug every time, and write down what you expected and what you got:
median([8.5, 11.0, 6.5, 7.0])gives 9.75, not 7.75.Shrink the input. Find the smallest input that still fails, so there is less to look at.
median([1, 2, 3, 4])gives 3.5, not 2.5, andmedian([1, 2])stops withIndexError. Lists with an odd number of values, such asmedian([3, 1, 2]), give the right answer.Form a hypothesis: a specific guess at the cause that a test can prove wrong. Only even lengths fail, and 3.5 is the mean of 3 and 4, so: “For an even length, the function averages the two values just above the middle instead of the two at the middle.”
Test the hypothesis. Decide what you’d see if it were true, then look. If it is true, for
[1, 2, 3, 4]the function addsordered[2]andordered[3], which are 3 and 4. If what you see disagrees, the hypothesis is wrong: form a new one with what you learned.Fix the cause, and confirm. Change the code, then run the reproduction, the smaller cases, and the cases that worked before.
Here, the two middle values of a list of length 4 are at positions 1 and 2, middle - 1 and
middle, so the fix is (ordered[middle - 1] + ordered[middle]) / 2. Then median([8.5, 11.0, 6.5, 7.0]) is 7.75, median([1, 2]) is 1.5, and median([3, 1, 2]) is still 2. Module 13 turns
each of these cases into a test that runs every time the code changes, so the bug can’t come
back unnoticed.
There are two ways to look at what a program is doing while it runs: print the values, or stop the program and look with a debugger.
Printing values¶
An f-string with = after an expression prints the expression and its value, which makes quick
checks easy to read:
ordered = sorted([1, 2, 3, 4])
middle = len(ordered) // 2
print(f"{middle=} {ordered[middle]=} {ordered[middle + 1]=}")middle=2 ordered[middle]=3 ordered[middle + 1]=4The values confirm the hypothesis. Remove such prints once the bug is fixed.
A debugger in the terminal: pdb¶
A debugger stops a program at a line you choose, a breakpoint, and lets you look at every
variable and then run the program one line at a time. Python comes with one, pdb. Put a call to
the built-in function breakpoint() on the line before the one you want to examine, in
median.py:
def median(values):
"""Return the middle value of values, or the mean of the two middle ones."""
ordered = sorted(values)
middle = len(ordered) // 2
breakpoint()
if len(ordered) % 2 == 0:
return (ordered[middle] + ordered[middle + 1]) / 2
return ordered[middle]
print(median([1, 2, 3, 4]))Run the script. pdb stops at the breakpoint and prompts with (Pdb); type a command after each
prompt:
> .../py101/m12/median.py(5)median()
-> breakpoint()
(Pdb) p ordered
[1, 2, 3, 4]
(Pdb) p middle
2
(Pdb) p ordered[middle], ordered[middle + 1]
(3, 4)
(Pdb) c
3.5The first two lines say where the program stopped: the file, line 5, and the function median,
then the line itself. Python 3.12 stops one line later, on line 6. The commands you’ll use most:
| Command | What it does |
|---|---|
p expression | Print the expression’s value, in the current function |
n (next) | Run the current line, without stopping inside the functions it calls |
s (step) | Run the current line, stopping inside a function it calls |
c (continue) | Run on, until the next breakpoint or the end |
l (list) and ll | Show the lines around the current one, or the whole function |
w (where) | Show the chain of calls, like a traceback |
q (quit) | Stop the debugger and the program |
Delete the breakpoint() line when you’re done, or the program will stop there every time it
runs.
The debugger in VS Code¶
VS Code’s debugger does the same with the mouse, and shows every variable at once. It comes with the Python extension, which you installed in Setting up your computer.
Open
median.pywithout itsbreakpoint()line. Click in the margin to the left of line 5’s number,if len(ordered) % 2 == 0:. A red dot marks the breakpoint.Select the down arrow beside the run button at the upper right of the editor, then Python Debugger: Debug Python File. The program runs and stops before line 5, which is highlighted.
In the Run and Debug view at the left, VARIABLES shows
values,ordered, andmiddle, and CALL STACK shows the chain of calls. Type an expression, such asordered[middle + 1], in the Debug Console at the bottom, and press Enter to see its value.Use the debug toolbar at the top of the window: Step Over (F10 on Windows and Linux) runs one line, Step Into (F11) goes into a function the line calls, Step Out returns from the current function, Continue (F5) runs to the next breakpoint, and Stop ends the program.
The debugger in JupyterLab¶
JupyterLab has a debugger for notebooks too. Turn it on with the bug button at the upper right of the notebook, whose tooltip says Enable Debugger. Click just left of a line number in a cell to set a breakpoint, and run a cell that reaches that line. The code stops there, and the debugger’s sidebar shows the Variables, the Callstack, whose buttons step through the code (Next, Step In, Step Out, and Continue), and the Breakpoints. Lab 12 uses it.
Common misconceptions¶
| Belief | What happens | Example that breaks it |
|---|---|---|
| The last frame of a traceback is where the bug is | It is where Python noticed the problem | average divides by zero because main gave report an empty list |
except Exception makes a program safe | It hides your own bugs as well | A typo, flaot, becomes “isn’t a number. Try again.” forever |
Wrapping a whole function in try is careful | A long try block gives the wrong message to errors from other lines | A ValueError from a later line is reported as bad input |
Returning None is gentler than raising | The error moves somewhere else, far from its cause | sum([8.5, None]) raises TypeError |
| A program that ran without an error is correct | Wrong answers raise nothing | median([8.5, 11.0, 6.5, 7.0]) returned 9.75 |
assert checks input | python -O removes every assert | Bad input passes unchecked |
| Debugging means changing code until the output looks right | Changes without a hypothesis can hide a bug | A median “fixed” by subtracting 1 from the result is right for one input only |
Summary¶
An exception stops a program unless something handles it. A traceback, read from the bottom up, gives the exception, the line that raised it, and the chain of calls that led there, oldest first.
tryandexcepthandle an exception. Name only the exceptions the code can recover from, and keep thetryblock to the lines that can raise them.elseruns when nothing was raised, andfinallyruns every time.Handle
KeyboardInterruptandEOFErroronce, at the top of an interactive program, to stop politely.raisestops a function and sends an exception to its caller. Say what was wrong, with the value, in its message. Raise when the caller shouldn’t carry on; return a special value only when “no answer” is normal and the caller will check for it.Find a bug by a method: reproduce it, shrink the input, form a hypothesis, test it with printed values or a debugger, then fix the cause and confirm.
Self-check¶
Answer each question before you open its answer.
A traceback ends with these lines. Which exception was raised, on which line of which function, and which function, on which line, called that one?
File ".../py101/m12/shop.py", line 15, in total result = result + cost(item, count) ~~~~^^^^^^^^^^^^^ File ".../py101/m12/shop.py", line 9, in cost return prices[item] * count ~~~~~~^^^^^^ KeyError: 'pears'Answer
A
KeyError, raised on line 9 ofshop.py, in the functioncost:'pears'isn’t a key inprices.totalcalledcoston line 15. The traceback doesn’t say whether the mistake is a missing price or an item that shouldn’t be in the basket; that is for you to decide.What is wrong with this code, and how would you fix it?
try: count = int(input("How many? ")) print(f"Ordering {count} boxes, {count * 6} eggs") place_order(count) except: print("Please type a whole number.")Answer
The bare
except:catches every exception, so any bug inplace_order, and even Ctrl+C, would be reported as “Please type a whole number.” Put only the conversion in thetryblock, nameValueError, and move the rest intoelseor after the statement:try: count = int(input("How many? ")) except ValueError: print("Please type a whole number.") else: print(f"Ordering {count} boxes, {count * 6} eggs") place_order(count)What does this print?
def check(text): try: number = int(text) except ValueError: return "bad" finally: print("checked", text) return number + 1 print(check("4")) print(check("four"))Answer
checked 4 5 checked four badfinallyruns before the function returns, even when thereturnis in theexceptclause, so eachcheckedline comes before the value it returns.Which should raise an exception, and which should return
None:find_station(stations, name), which looks up a station that the user may have misspelled, andread_config(path), which reads a settings file that the program can’t run without?Answer
find_stationcan returnNone: “no such station” is a normal result, and its caller will check for it to tell the user.read_configshould raise: without its settings the program can’t do its job, and aNonethat a caller forgot to check would fail later, far from the cause. Either answer needs a docstring that says what happens.A program’s report shows the wrong total for a file of 10,000 rows. What are your first two steps, and why that order?
Answer
First reproduce it: run the program on the file and write down the total you expected and the one you got. Then shrink the input: cut the file down, for example by halves, until you find the fewest rows that still give a wrong total. A bug you can’t reproduce can’t be confirmed as fixed, and a 3-row input is far easier to trace by hand, by print, or in a debugger than 10,000 rows.
Further reading¶
The Python Tutorial, chapter 8, Errors and Exceptions, sections 8.1–8.4 and 8.7. Python’s own explanation of everything in the first half of this module.
The Python documentation’s Built-in Exceptions, which lists every exception and ends with the hierarchy that shows which kinds of exception belong to which.
The pdb documentation, for every debugger command, and VS Code’s Python debugging in VS Code, for more on its debugger.
Al Sweigart, Automate the Boring Stuff with Python, 3rd edition, chapter 5, Debugging. Raising exceptions, tracebacks, and a debugger, with another set of examples.
Andreas Zeller, The Debugging Book, Introduction to Debugging. The scientific method applied to debugging, at more depth, for when you want more than this module’s five steps.
MIT’s The Missing Semester, Debugging and Profiling. Debuggers and other tools, from the terminal.