Skip to content

Module 19 · Debugging, Testing and Best Practices — topic 3 of 15

Reading tracebacks

Understanding Python's error reports: the parts of a traceback, reading from the bottom up, following the call chain, chained exceptions ('during handling' and 'direct cause'), and inspecting tracebacks with the traceback module.

Beginner 8 min read·Lesson 281 of 306 in Python Programming

Learning objectives

  • Identify the parts of a traceback
  • Locate the line and call chain that caused an error
  • Interpret chained exceptions

Definition

A traceback is the report Python prints when an exception is not handled. It lists the chain of function calls that led to the error, most recent call last, and ends with the exception type and message.

Introduction

A wall of red text looks scary, but a traceback is the most helpful thing Python gives you: it says exactly what went wrong and where.

Why it matters

Reading tracebacks quickly is the single most useful debugging skill for Python programmers.

Detailed explanation

Start at the bottom: the last line gives the exception type and message, such as ValueError: invalid literal for int() with base 10: 'twenty'.

Above it, each frame shows a file, a line number, a function name and the source line. The last frame is where the exception was raised.

Read upwards to see who called whom. The first frame of your own code near the bottom is usually where to start looking.

Frames inside libraries or the standard library often aren't the problem; the bug is usually in how your code called them.

Modern Python marks the exact failing expression with ^ characters under the line.

'During handling of the above exception, another exception occurred' means a new error happened inside an except block. 'The above exception was the direct cause' appears with raise ... from.

The traceback module lets programs format or inspect tracebacks, for example to log them: traceback.format_exc(), traceback.extract_tb().

Search engines work well with the last line of a traceback (without your file paths).

Syntax

Text
Traceback (most recent call last):
File "app.py", line 9, in <module>
load({"age": "twenty"})
File "app.py", line 5, in load
return parse_age(record["age"])
File "app.py", line 2, in parse_age
return int(text)
ValueError: invalid literal for int() with base 10: 'twenty'
  • Read the last line first.
  • Frames show the call chain.
  • Find the first frame in your code.

Code examples

Inspecting the call chain

Python
import traceback
def parse_age(text):
return int(text)
def load(record):
return parse_age(record["age"])
try:
load({"age": "twenty"})
except ValueError as e:
frames = traceback.extract_tb(e.__traceback__)
print([f.name for f in frames])
print(f"{type(e).__name__}: {e}")
Output
['<module>', 'load', 'parse_age']
ValueError: invalid literal for int() with base 10: 'twenty'

A traceback with a marker

Text
Traceback (most recent call last):
File "report.py", line 4, in <module>
print(totals["march"] / count)
~~~~~~^^^^^^^^^
KeyError: 'march'

The ^ characters point at the part of the line that failed: looking up 'march' in totals.

More examples

Chained exceptions

Python
import traceback
class ConfigError(Exception):
pass
def read_port(cfg):
try:
return int(cfg["port"])
except KeyError as e:
raise ConfigError("port missing") from e
try:
read_port({})
except ConfigError as e:
print("".join(traceback.format_exception_only(e)).strip())
print("caused by:", repr(e.__cause__))
Output
ConfigError: port missing
caused by: KeyError('port')

Step-by-step explanation

  • read_port translates a low-level KeyError into a meaningful ConfigError.
  • Printed as a full traceback, Python would show both exceptions joined by 'The above exception was the direct cause of the following exception'.
  • __cause__ gives programmatic access to the original error.

Expected output

Running “Chained exceptions” prints exactly:

TextOutput
ConfigError: port missing
caused by: KeyError('port')

Practical applications

  • Diagnosing crash reports from users.
  • Logging full tracebacks on servers with logger.exception.

Best practices

  • Read tracebacks bottom-up.
  • Find the first frame in your own code.
  • Log full tracebacks rather than vague messages.

Common mistakes

Reading only the first line

Avoid

# 'Traceback (most recent call last)' — no idea what happened

Prefer

# read the last line, then the frames above it

The important information is at the bottom.

Hiding tracebacks

Avoid

except Exception:
print("something went wrong")

Prefer

except Exception:
logging.exception("failed to load report")

Swallowing the traceback throws away the evidence.

Important notes

  • python -X faulthandler prints tracebacks even for hard crashes.

Key takeaways

  • Tracebacks list calls, most recent last.
  • The last line is the error type and message.
  • Chained exceptions show causes.

Try it yourself

  1. 1
    Write a three-function program that raises an error, run it, and annotate each line of the traceback.
  2. 2
    Use traceback.format_exc() to save an error report to a file.

Finished reading? Mark it complete to update your dashboard.

Suggested practice

1 question test this exact topic. Answers and explanations are revealed after you submit.

  • AdvancedWhere should you usually start reading a Python traceback?
Practise this topic