Stack traces
suggest changeWhen an exception is not caught, Python prints a stack trace (Python calls it a traceback) and exits. The traceback lists the chain of function calls that led to the error, and it is usually the fastest way to find a bug.
This article covers:
- how to read a traceback, including chained exceptions, notes and exception groups
- the
tracebackmodule: printing, formatting and inspecting tracebacks without crashing - printing the current call stack when there is no exception
- hooks for uncaught exceptions in the main program and in threads
- logging tracebacks and stacks
faulthandlerfor hangs and hard crashes
All examples were run with Python 3.13. Python 3.13 colors tracebacks in a terminal; set the environment variable PYTHON_COLORS=0 (or NO_COLOR=1) to turn colors off.
Reading a traceback
Save this as app.py and run it:
def load_config(path):
with open(path) as f:
return parse(f.read())
def parse(text):
settings = {}
for line in text.splitlines():
key, value = line.split("=")
settings[key.strip()] = value.strip()
return settings
def main():
config = {"port": "8080"}
timeout = int(config["timeout"])
print(timeout)
main()
Traceback (most recent call last):
File "app.py", line 17, in <module>
main()
~~~~^^
File "app.py", line 14, in main
timeout = int(config["timeout"])
~~~~~~^^^^^^^^^^^
KeyError: 'timeout'
How to read it:
- Read from the bottom up. The last line is the exception type and message:
KeyError: 'timeout'. That tells you what went wrong. - "most recent call last" means frames are listed from the outermost call (top) to the place where the exception was raised (bottom).
- Each frame shows the file, line number and function name (
<module>is top-level code), followed by the source line. - The
~~~^^^markers (Python 3.11+) point at the exact sub-expression that failed. Hereconfig["timeout"]failed, not the call toint(). - Functions that were never called (
load_config,parse) do not appear. A traceback shows only the active call chain at the moment of the error.
The carets matter most when one line does several things:
def average(values):
return sum(values) / len(values)
def report(data):
return {name: average(scores) for name, scores in data.items()}
print(report({"ann": [90, 80], "bob": []}))
Traceback (most recent call last):
File "example.py", line 7, in <module>
print(report({"ann": [90, 80], "bob": []}))
~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "example.py", line 5, in report
return {name: average(scores) for name, scores in data.items()}
~~~~~~~^^^^^^^^
File "example.py", line 2, in average
return sum(values) / len(values)
~~~~~~~~~~~~^~~~~~~~~~~~~
ZeroDivisionError: division by zero
user = {"profile": {"address": None}}
print(user["profile"]["address"]["city"])
Traceback (most recent call last):
File "example.py", line 2, in <module>
print(user["profile"]["address"]["city"])
~~~~~~~~~~~~~~~~~~~~~~~~~~^^^^^^^^
TypeError: 'NoneType' object is not subscriptable
The markers show that user["profile"]["address"] was None, so the ["city"] lookup failed.
In real programs, the bottom frames are often inside the standard library or a third-party package. The bug is usually in the last frame that belongs to your code, so scan upward from the bottom until you reach one of your files.
Deep recursion
For a RecursionError, Python collapses identical frames instead of printing a thousand of them:
def countdown(n):
return countdown(n - 1)
countdown(10)
Traceback (most recent call last):
File "example.py", line 4, in <module>
countdown(10)
~~~~~~~~~^^^^
File "example.py", line 2, in countdown
return countdown(n - 1)
File "example.py", line 2, in countdown
return countdown(n - 1)
File "example.py", line 2, in countdown
return countdown(n - 1)
[Previous line repeated 996 more times]
RecursionError: maximum recursion depth exceeded
Chained exceptions
If an exception is raised while another is being handled, Python prints both tracebacks. The wording between them tells you how they are related.
With raise ... from e (see Chain exceptions with raise from), the original exception is the explicit cause:
class ConfigError(Exception):
pass
def read_port(config):
try:
return int(config["port"])
except KeyError as e:
raise ConfigError("port is not configured") from e
read_port({})
Traceback (most recent call last):
File "example.py", line 6, in read_port
return int(config["port"])
~~~~~~^^^^^^^^
KeyError: 'port'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "example.py", line 10, in <module>
read_port({})
~~~~~~~~~^^^^
File "example.py", line 8, in read_port
raise ConfigError("port is not configured") from e
ConfigError: port is not configured
If the second exception happens by accident inside an except block, you get "During handling of the above exception". This usually points to a bug in the error handling code itself:
def cleanup():
raise RuntimeError("cleanup failed")
try:
1 / 0
except ZeroDivisionError:
cleanup()
Traceback (most recent call last):
File "example.py", line 5, in <module>
1 / 0
~~^~~
ZeroDivisionError: division by zero
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "example.py", line 7, in <module>
cleanup()
~~~~~~~^^
File "example.py", line 2, in cleanup
raise RuntimeError("cleanup failed")
RuntimeError: cleanup failed
The first case sets __cause__ on the new exception and the second sets __context__. Use raise ... from None to hide the original exception when it is only an implementation detail:
def read_port(config):
try:
return int(config["port"])
except KeyError:
raise ValueError("port is not configured") from None
read_port({})
Traceback (most recent call last):
File "example.py", line 7, in <module>
read_port({})
~~~~~~~~~^^^^
File "example.py", line 5, in read_port
raise ValueError("port is not configured") from None
ValueError: port is not configured
Adding context with notes
Since Python 3.11, add_note() attaches extra text to an exception. Notes are printed after the exception message, which helps when a low-level error needs context about what the program was doing:
def import_row(row_num, row):
try:
return int(row["amount"])
except ValueError as e:
e.add_note(f"while importing row {row_num}: {row!r}")
raise
import_row(17, {"amount": "12,50"})
Traceback (most recent call last):
File "example.py", line 8, in <module>
import_row(17, {"amount": "12,50"})
~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^
File "example.py", line 3, in import_row
return int(row["amount"])
ValueError: invalid literal for int() with base 10: '12,50'
while importing row 17: {'amount': '12,50'}
A bare raise re-raises the same exception object, so the traceback still points at the line that originally failed.
Exception groups
An ExceptionGroup (Python 3.11+) bundles several exceptions together. Its traceback is drawn as a tree, with one numbered branch per sub-exception:
def validate(user):
errors = []
if not user.get("name"):
errors.append(ValueError("name is required"))
if user.get("age", 0) < 0:
errors.append(ValueError("age must be >= 0"))
if errors:
raise ExceptionGroup("invalid user", errors)
validate({"name": "", "age": -1})
+ Exception Group Traceback (most recent call last):
| File "example.py", line 10, in <module>
| validate({"name": "", "age": -1})
| ~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^
| File "example.py", line 8, in validate
| raise ExceptionGroup("invalid user", errors)
| ExceptionGroup: invalid user (2 sub-exceptions)
+-+---------------- 1 ----------------
| ValueError: name is required
+---------------- 2 ----------------
| ValueError: age must be >= 0
+------------------------------------
Printing a traceback without crashing
Often you want to catch an exception, record the full traceback and keep going. The traceback module does that.
traceback.print_exc() prints the exception currently being handled. It writes to sys.stderr by default; pass file= to send it somewhere else:
import sys
import traceback
def divide(a, b):
return a / b
try:
divide(1, 0)
except ZeroDivisionError:
traceback.print_exc(file=sys.stdout)
print("program continues")
Traceback (most recent call last):
File "example.py", line 8, in <module>
divide(1, 0)
~~~~~~^^^^^^
File "example.py", line 5, in divide
return a / b
~~^~~
ZeroDivisionError: division by zero
program continues
traceback.format_exc() returns the same text as a string, which you can store in a database, send in an error report, or show in a UI:
import traceback
def parse_age(text):
return int(text)
try:
parse_age("forty")
except ValueError:
text = traceback.format_exc()
print(type(text).__name__, len(text.splitlines()), "lines")
print(text.splitlines()[-1])
str 7 lines
ValueError: invalid literal for int() with base 10: 'forty'
print_exc() and format_exc() only work inside an except block. To format an exception object you saved earlier, use print_exception() or format_exception(). Since Python 3.10 they accept the exception as their only argument. The traceback is stored on the exception in its __traceback__ attribute:
import traceback
def fail():
raise KeyError("missing")
try:
fail()
except KeyError as e:
saved = e
# later, outside the except block
print("".join(traceback.format_exception(saved)))
print(traceback.format_exception_only(saved))
Traceback (most recent call last):
File "example.py", line 7, in <module>
fail()
~~~~^^
File "example.py", line 4, in fail
raise KeyError("missing")
KeyError: 'missing'
["KeyError: 'missing'\n"]
format_exception() returns a list of strings (some of them contain several lines), so join them before printing. format_exception_only() returns just the final Type: message part.
Limiting the number of frames
Use limit= to shorten long tracebacks. A positive limit keeps the outermost frames and a negative limit keeps the innermost frames, which are usually the more useful ones:
import sys
import traceback
def level(n):
if n == 0:
raise RuntimeError("bottom reached")
level(n - 1)
try:
level(5)
except RuntimeError:
print("-- limit=2 (outermost frames)")
traceback.print_exc(limit=2, file=sys.stdout)
print("-- limit=-2 (innermost frames)")
traceback.print_exc(limit=-2, file=sys.stdout)
-- limit=2 (outermost frames)
Traceback (most recent call last):
File "example.py", line 10, in <module>
level(5)
~~~~~^^^
File "example.py", line 7, in level
level(n - 1)
~~~~~^^^^^^^
RuntimeError: bottom reached
-- limit=-2 (innermost frames)
Traceback (most recent call last):
File "example.py", line 7, in level
level(n - 1)
~~~~~^^^^^^^
File "example.py", line 6, in level
raise RuntimeError("bottom reached")
RuntimeError: bottom reached
Inspecting traceback frames
A traceback is a linked list of frames. traceback.extract_tb() turns it into a list of FrameSummary objects with filename, lineno, name and line attributes. This is handy for building custom error reports:
import traceback
def fail():
raise ValueError("bad input")
try:
fail()
except ValueError as e:
tb = e.__traceback__
for frame in traceback.extract_tb(tb):
print(f"{frame.filename}:{frame.lineno} in {frame.name}: {frame.line}")
example.py:7 in <module>: fail()
example.py:4 in fail: raise ValueError("bad input")
You can also walk the raw traceback objects yourself. Each one has tb_next, tb_lineno and tb_frame, and the frame gives access to the local variables at the moment of the error. TracebackException with capture_locals=True prints those locals in each frame:
import traceback
def process(order):
total = order["qty"] * order["price"]
return total
def handle(order):
try:
return process(order)
except TypeError as e:
tb = e.__traceback__
while tb.tb_next: # walk to the innermost frame
tb = tb.tb_next
print("failed in", tb.tb_frame.f_code.co_name, "line", tb.tb_lineno)
print("locals:", tb.tb_frame.f_locals)
print()
te = traceback.TracebackException.from_exception(e, capture_locals=True)
print("".join(te.format()))
handle({"qty": 3, "price": None})
failed in process line 4
locals: {'order': {'qty': 3, 'price': None}}
Traceback (most recent call last):
File "example.py", line 9, in handle
return process(order)
e = TypeError("unsupported operand type(s) for *: 'int' and 'NoneType'")
order = {'qty': 3, 'price': None}
tb = <traceback object at 0x00000209DDA0B740>
File "example.py", line 4, in process
total = order["qty"] * order["price"]
~~~~~~~~~~~~~^~~~~~~~~~~~~~~~
order = {'qty': 3, 'price': None}
TypeError: unsupported operand type(s) for *: 'int' and 'NoneType'
Be careful with captured locals in production logs: they can contain passwords, tokens and personal data.
A traceback keeps every frame on it alive, along with all of their local variables. If you store exceptions for a long time (for example in a list of errors), you keep that memory alive too. Store the formatted string instead, or call traceback.clear_frames(tb) when you no longer need the locals.
Printing the current stack
Sometimes there is no exception, but you want to know how the program got to a certain line. traceback.print_stack() prints the current call stack and traceback.extract_stack() returns it as a list:
import sys
import traceback
def outer():
inner()
def inner():
traceback.print_stack(file=sys.stdout)
print("---")
for frame in traceback.extract_stack():
print(frame.name, frame.lineno)
outer()
File "example.py", line 13, in <module>
outer()
File "example.py", line 5, in outer
inner()
File "example.py", line 8, in inner
traceback.print_stack(file=sys.stdout)
---
<module> 13
outer 5
inner 10
For a quick "who called me?", inspect.stack() returns frame records with function, filename and lineno. Index 0 is the current function and index 1 is its caller:
import inspect
def who_called_me():
caller = inspect.stack()[1]
return f"{caller.function} at line {caller.lineno}"
def handler():
print(who_called_me())
handler()
handler at line 8
inspect.stack() reads source files for every frame, so it is slow. Don't call it in hot code paths.
Logging tracebacks and stacks
In applications, send tracebacks to the log instead of printing them. logger.exception() logs at ERROR level and appends the current traceback (see Logging exceptions):
import logging
import sys
logging.basicConfig(stream=sys.stdout, format="%(levelname)s %(message)s")
log = logging.getLogger(__name__)
try:
{}["missing"]
except KeyError:
log.exception("lookup failed")
ERROR lookup failed
Traceback (most recent call last):
File "example.py", line 8, in <module>
{}["missing"]
~~^^^^^^^^^^^
KeyError: 'missing'
To log the current call stack without an exception, pass stack_info=True to any logging call:
import logging
import sys
logging.basicConfig(stream=sys.stdout, format="%(levelname)s %(message)s")
log = logging.getLogger(__name__)
def charge(amount):
if amount > 1000:
log.warning("large charge: %s", amount, stack_info=True)
def checkout():
charge(5000)
checkout()
WARNING large charge: 5000
Stack (most recent call last):
File "example.py", line 14, in <module>
checkout()
File "example.py", line 12, in checkout
charge(5000)
File "example.py", line 9, in charge
log.warning("large charge: %s", amount, stack_info=True)
Handling uncaught exceptions
When an exception reaches the top level, Python calls sys.excepthook(exc_type, exc, tb). The default hook prints the traceback to stderr. Replace it to write crash reports, send errors to a monitoring service, or show a friendlier message:
import sys
import traceback
def log_uncaught(exc_type, exc, tb):
with open("crash.log", "w") as f:
traceback.print_exception(exc_type, exc, tb, file=f)
print(f"fatal: {exc_type.__name__}: {exc} (details in crash.log)", file=sys.stderr)
sys.excepthook = log_uncaught
def start():
raise ConnectionError("database unreachable")
start()
fatal: ConnectionError: database unreachable (details in crash.log)
crash.log now contains:
Traceback (most recent call last):
File "example.py", line 14, in <module>
start()
~~~~~^^
File "example.py", line 12, in start
raise ConnectionError("database unreachable")
ConnectionError: database unreachable
The program still exits with status 1. The original hook is always available as sys.__excepthook__ if you want to call it from your own hook.
Exceptions in threads do not go through sys.excepthook. An uncaught exception ends only that thread, and Python calls threading.excepthook with an object that has exc_type, exc_value, exc_traceback and thread attributes:
import threading
def worker():
raise ValueError("worker failed")
def on_thread_error(args):
print(f"thread {args.thread.name} died: {args.exc_type.__name__}: {args.exc_value}")
threading.excepthook = on_thread_error
t = threading.Thread(target=worker, name="worker-1")
t.start()
t.join()
print("main thread still running")
thread worker-1 died: ValueError: worker failed
main thread still running
With concurrent.futures, the exception is stored in the Future and re-raised by future.result(), so you get the traceback in the thread that asks for the result.
Hangs and crashes: faulthandler
A normal traceback needs the interpreter to be running fine. It cannot help when a program hangs forever, or when a C extension crashes the process with a segmentation fault. The faulthandler module dumps the Python stack of every thread in those situations.
dump_traceback_later() dumps the stack if the program is still running after a timeout. With exit=True it also ends the process, which is useful for finding where a test or script gets stuck:
import faulthandler
import sys
import time
def wait_for_lock():
time.sleep(3) # pretend this hangs
faulthandler.dump_traceback_later(1, exit=True, file=sys.stdout)
wait_for_lock()
Timeout (0:00:01)!
Thread 0x000040a4 (most recent call first):
File "example.py", line 6 in wait_for_lock
File "example.py", line 9 in <module>
Note that faulthandler prints frames most recent call first, the opposite order from a normal traceback. Call faulthandler.cancel_dump_traceback_later() once the risky section completes.
faulthandler.enable() installs handlers for fatal signals such as SIGSEGV. Without it, a crash in native code kills the process with only "Segmentation fault". With it, you see which Python code was running:
import ctypes
import faulthandler
faulthandler.enable()
def crash():
ctypes.string_at(0) # read from address 0
crash()
Output on Linux:
Fatal Python error: Segmentation fault
Current thread 0x00007f8adfe741c0 [python3] (most recent call first):
File "/usr/lib/python3.14/ctypes/__init__.py", line 621 in string_at
File "example.py", line 7 in crash
File "example.py", line 9 in <module>
...
Segmentation fault
Python 3.14 also prints the C-level stack after the Python frames (shown as ... above). You can turn faulthandler on without changing code by running python -X faulthandler app.py or setting PYTHONFAULTHANDLER=1. On Unix, faulthandler.register(signal.SIGUSR1) lets you dump the stacks of a running process on demand with kill -USR1 <pid>.
Summary
| Task | Use |
|---|---|
| Print the current exception and continue | traceback.print_exc() |
| Get the current traceback as a string | traceback.format_exc() |
| Format a saved exception | traceback.format_exception(exc) |
| Access the traceback of an exception | exc.__traceback__ |
| Shorten a traceback | limit=-N (innermost N frames) |
| List frames programmatically | traceback.extract_tb(tb) |
| Show local variables in each frame | TracebackException.from_exception(e, capture_locals=True) |
| Print the call stack without an exception | traceback.print_stack() |
| Find the caller of a function | inspect.stack()[1] |
| Log an exception with traceback | logger.exception(msg) |
| Log the current stack | logger.warning(msg, stack_info=True) |
| Add context to an exception | exc.add_note(text) (3.11+) |
| Handle uncaught exceptions | sys.excepthook, threading.excepthook |
| Debug hangs and segfaults | faulthandler, python -X faulthandler |
To examine a failing program interactively instead of reading a static traceback, use the Python debugger: python -m pdb app.py stops at the frame where an uncaught exception was raised.