đ 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?
- â ī¸ Basic Exception Output
- đ§ Using traceback
- đĻ extract_tb()
- đ¯ Getting the Failed Function Name
- đ ī¸ Useful Debugging Patterns
- đŽ Real 42 Examples
- â ī¸ Common Beginner Mistakes
- đ Best Practices
- đ Final Notes
đ 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