🎓 A1Learner
🔍
0 of 52 lessons completed

Python Reading a Traceback

A traceback is the report Python prints after an error. Read it from the bottom up.

The last line names the error

format_exc() gives the report as text. The last line names the missing key.

import traceback

try:
    ages = {"Ada": 30}
    print(ages["Bob"])
except KeyError:
    print(traceback.format_exc(), end="")

The lines above show the call

double uses a name that was never made. The middle line names double and its line.

import traceback

def double(n):
    return n + unknown

try:
    print(double(3))
except NameError:
    print(traceback.format_exc(), end="")

Read the last line first

The text abc cannot become a number. The last line says ValueError.

import traceback

try:
    print(int("abc"))
except ValueError:
    print(traceback.format_exc(), end="")

Example

import traceback

def price_each(count):
    return 100 / count

def bill(count):
    return price_each(count) * 2

try:
    print("Bill:", bill(0))
except ZeroDivisionError:
    report = traceback.format_exc()
    print(report)
    print("Last line:", report.strip().split("\n")[-1])

Key points

  • Traceback: the report Python prints after an error
  • Use the last line to name the error
  • The last line holds the error type and its message
  • The lines above it show the calls that led there
  • Each middle line names one call and its line number
  • The top line says only that a traceback happened

In this example, bill calls price_each. price_each divides by zero. The report lists both calls in order. The last line names the error. The last print pulls that line out alone.

Note

Short runs show the file name as <string>.

Try it Yourself

Edit the code, then press Run.

Running is simulated · Python Playground

Exercise

A traceback ends with KeyError: 'age'. What does that line tell you?