Skip to content
FollowtheDamnCode

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:

  1. Last line — the exception's type (ZeroDivisionError) and a message. This is what went wrong.
  2. Lines above — where: the file, the line number, and the code on that line.
  3. When functions call functions, the traceback lists every call on the way, outermost first, the actual failure last.

The ones you'll meet most

ExceptionTypical cause
NameErrorusing a name that doesn't exist (often a typo)
TypeErrorthe wrong type for an operation: "a" + 1
ValueErrorright type, bad value: int("abc")
IndexErrorlist or string position out of range
KeyErrordictionary key not there
ZeroDivisionErrordividing by zero
AttributeErrora method that type doesn't have: 5.upper()
FileNotFoundErroropening a file that doesn't exist
Fix the bug: print every name, then "done"
names = ["Ada", "Grace"]
for i in range(3):
    print(names[i])
print("done")
output
Ada
Grace
done

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

Fix the bug: read the traceback, then fix the typo
total = 0
for n in [1, 2, 3]:
    totl = total + n
    total = totl
print(totall)
output
6

Run 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?