Reading a stack trace
A is the breadcrumb trail of function calls that led to a failure.
Reach for it whenRead the stack trace before adding print statements; start at the final exception and your nearest application frame, not the first library frame.
Read it from the bottom up. The last line names the kind of problem and describes it — for example NameError: name 'totl' is not defined, which means you misspelt a variable. That bottom line is usually all you need.
Above it is the traceback: the chain of function calls that led to the failure, oldest at the top, most recent at the bottom. When your own code called a library that failed, this chain shows which of your lines started it.
raise ValueError("n must be positive")- Signals a failure yourself, with a message the traceback will show.
import traceback- The module for handling tracebacks as data.
traceback.print_exc()- Prints the current exception and its traceback from inside an except block.
raise ValueError("bad row") from err- Chains a new error onto the original, so the traceback shows both causes.
Each frame names a file, line, and function on the path to failure. Read from the final exception upward to find the immediate cause, then use earlier frames to learn who supplied the bad state.
Python unwinds active calls after an exception is not handled, recording each frame as it goes. The bottom line names the exception class and message; it is the compact summary, not incidental noise.
A conversion can fail because malformed text entered five functions earlier. Treat the traceback as the location where the invariant was detected, then trace the suspect value backward to where it was created.
- Sentry — groups captured exceptions and displays their with source context.
- pytest — shows the failing assertion and a filtered Python traceback for a failed test.
- "The top line is where the bug is." Correction: the final exception and last relevant frame are usually the best start.
- "Every frame is broken." Correction: frames show the call path; often only one assumption along it is wrong.