Course outline · 0% complete

0/29 lessons0%

Course overview →

Anatomy of a Traceback

lesson 8-1 · ~10 min · 23/29

Quiz

Warm-up from lesson 7-2: your bug repro is a 40-line input file. Before forming hypotheses, what does the methodology say to do with it?

The crash report, read properly

When Python crashes it prints a traceback: a listing of every function call that was active at the moment of the crash, ending with the error itself. It exists because the crashing line alone is rarely enough to diagnose anything — you also need to know how execution got there, and the traceback records exactly that chain of calls. Beginners scroll past it as noise; professionals read it first, because it is the cheapest, most precise evidence a bug will ever hand you. Here is one:

Traceback (most recent call last):
  File "app.py", line 10, in <module>
    print(total_cents(["4.20", "banana"]))
  File "app.py", line 6, in total_cents
    total += to_cents(p)
  File "app.py", line 2, in to_cents
    return int(float(text) * 100)
ValueError: could not convert string to float: 'banana'

Read it bottom-up:

  1. last line: what went wrong and why. Type ValueError, message names the guilty value, 'banana'
  2. frame above it: where it happened, file, line number, and the exact source line
  3. the chain upward: how execution got there, each frame called the one below. The header says most recent call last, so the top is the outermost call

The crash site is not always the bug site: to_cents is innocent here, someone upstream put 'banana' in a price list. The chain is what lets you walk upstream.

outermost call, in <module>called total_cents, line 6called to_cents, line 2 (crash site)ValueError: the what and the whyread upwardstart at the last line, then walk the call chain up
Traceback anatomy: the last line names the error, the frames above show how execution got there.

Code exercise · python

Run the exact program from the traceback above, with the crash caught so we can print the same diagnosis the last line of the traceback would show.

Quiz

A 30-line traceback lands in your terminal. Which single line do you read first?

Code exercise · python

Your turn. Run this and read the crash: TypeError, can only concatenate str (not "int") to str, pointing at the return line. Fix describe using an f-string so it prints: Ada is 36 years old