Skip to content

๐Ÿ” Python Traceback & Debugging Guide

Beginner-friendly documentation about Python tracebacks, exception debugging, and useful debugging patterns.

This document explains: - what a traceback is - how exceptions work - traceback module - extracting function names - debugging helpers - useful debugging patterns


๐Ÿ“š Table of Contents


๐Ÿ“– What is a Traceback?

A traceback is: - Python's error report

It shows: - where the error happened - which functions were called - the exception type - the error message


Example Traceback

Traceback (most recent call last):
  File "main.py", line 10, in <module>
    divide(10, 0)
  File "main.py", line 5, in divide
    return a / b

ZeroDivisionError: division by zero

โš ๏ธ Basic Exception Output

try:
    value = 10 / 0

except Exception as e:
    print(type(e).__name__)
    print(e)

Output

ZeroDivisionError
division by zero

๐Ÿง  Using traceback

import traceback

Useful for: - advanced debugging - custom error displays - logging


๐Ÿ“ฆ extract_tb()

traceback.extract_tb() extracts traceback information.


Example

import traceback

try:
    value = 10 / 0

except Exception as e:

    tb = traceback.extract_tb(e.__traceback__)

    print(tb)

๐ŸŽฏ Getting the Failed Function Name

import traceback

try:
    value = 10 / 0

except Exception as e:

    tb = traceback.extract_tb(e.__traceback__)

    print(f"Failed on the function: {tb[-1].name}")
    print(f"{type(e).__name__}: {e}")

Example Output

Failed on the function: divide
ZeroDivisionError: division by zero

๐Ÿ› ๏ธ Useful Debugging Patterns

Showing the Exception Type

print(type(e).__name__)

Showing the Exception Message

print(e)

Combining Both

print(f"{type(e).__name__}: {e}")

๐ŸŽฎ Real 42 Examples

Parser Errors

except Exception as e:

    tb = traceback.extract_tb(e.__traceback__)

    print(f"Failed on function: {tb[-1].name}")

Invalid Config

ValueError: Invalid WIDTH

Invalid Coordinates

MapParserError: Invalid coordinates

โš ๏ธ Common Beginner Mistakes

โŒ Using Bare except

Bad:

except:

โŒ Ignoring Tracebacks

The traceback usually shows: - the REAL problem location


โŒ Printing Huge Tracebacks Everywhere

Too much debugging output can: - clutter logs - make debugging harder


๐Ÿ“š Best Practices

  • Read traceback lines carefully
  • Look at the LAST function call first
  • Print exception types clearly
  • Use meaningful error messages
  • Add debugging progressively

๐Ÿ“š Final Notes

Understanding tracebacks is essential for Python development.

Good traceback handling helps: - locate bugs quickly - improve error reporting - simplify debugging