Exceptions and Tracebacks
What happens when code fails, and how to read the report.
4 minute read
Big idea
When something goes wrong while a program runs, Python raises an exception: it stops and prints a traceback saying what went wrong and where. Reading tracebacks is a skill — and the fastest way to fix bugs.
Two kinds of error
- Syntax errors — the code isn't valid Python (a missing colon or bracket). Python refuses to start at all.
- Exceptions — the code is valid, but something fails while it runs: dividing by zero, a missing key, text that isn't a number.
print("Starting")
print(10 / 2)
print(10 / 0)
print("Never printed")
This prints Starting and 5.0 — everything before the bad line runs. Then Python stops and prints something like this:
Traceback (most recent call last):
File "main.py", line 3, in <module>
print(10 / 0)
~~~^~~
ZeroDivisionError: division by zero
Reading a traceback
Read it from the bottom up:
- Last line — the exception's type (
ZeroDivisionError) and a message. This is what went wrong. - Lines above — where: the file, the line number, and the code on that line.
- When functions call functions, the traceback lists every call on the way, outermost first, the actual failure last.
The ones you'll meet most
| Exception | Typical cause |
|---|---|
NameError | using a name that doesn't exist (often a typo) |
TypeError | the wrong type for an operation: "a" + 1 |
ValueError | right type, bad value: int("abc") |
IndexError | list or string position out of range |
KeyError | dictionary key not there |
ZeroDivisionError | dividing by zero |
AttributeError | a method that type doesn't have: 5.upper() |
FileNotFoundError | opening a file that doesn't exist |
names = ["Ada", "Grace"]
for i in range(3):
print(names[i])
print("done")output
Ada
Grace
doneRun and edit it in the app.
Run it first and read the traceback: the third round raises IndexError: list index out of range, so "done" never prints. There are only two names — loop over range(len(names)), or better, for name in names:.
total = 0
for n in [1, 2, 3]:
totl = total + n
total = totl
print(totall)output
6Run and edit it in the app.
The traceback ends NameError: name 'totall' is not defined. Did you mean: 'total'? — Python even suggests the fix.
Which exception does int("twelve") raise?
Watch it
Think of it like
A smoke alarm. It doesn't just beep — it tells you which room. The last line of the traceback is the alarm's label; the lines above are the floor plan showing how you got there.
Key terms
- Exception — An error raised while the program runs.
- Traceback — Python's report of the error and the chain of calls that led to it.
- Raise — To signal an exception.
Check yourself
Where should you start reading a traceback?
What raises an IndexError?
What raises a NameError?