traceback

Understanding and using the traceback module in Python for debugging
python
programming
Published

June 30, 2025

One of the most useful tools in Python for debugging is the traceback module. It provides a way to extract, format, and print stack traces of Python programs. This can be incredibly helpful when you encounter an error and need to understand where it originated. Let’s first consider a simple example that does not handle exceptions properly, and provide no traceback information.

def divide(a, b):
    return a / b

try:
    result = divide(10, 0)
except Exception as e:
    print("An error occurred:", e)
An error occurred: division by zero

When you run this code, it will output:

An error occurred: division by zero

However, it does not give you any information about where the error occurred in the code. To get more detailed information, you can use the traceback module.

import traceback

def divide(a, b):
    return a / b

try:
    result = divide(10, 0)
except Exception as e:
    print("An error occurred:", e)
    traceback.print_exc()
An error occurred: division by zero
Traceback (most recent call last):
  File "/var/folders/mj/10qd82nj4gz6drm4xmsg30r40000gn/T/ipykernel_81933/1302253731.py", line 7, in <module>
    result = divide(10, 0)
  File "/var/folders/mj/10qd82nj4gz6drm4xmsg30r40000gn/T/ipykernel_81933/1302253731.py", line 4, in divide
    return a / b
           ~~^~~
ZeroDivisionError: division by zero

When you run this code, it will output:

An error occurred: division by zero
Traceback (most recent call last):
  File "script.py", line 8, in <module>
    result = divide(10, 0)
  File "script.py", line 3, in divide
    return a / b
ZeroDivisionError: division by zero