traceback
- Python course
- Intermediate
- Lesson 86/116
- 4 min
Learn stack traces with the traceback module.
The traceback module
To see the full call stack of an error you use the traceback module. You import it with import traceback and get the stack trace at the error moment as a string with traceback.format_exc().
This string shows which file and line the error started on; it lists each call frame in order. It's useful for error logging in production applications; not shown to the user but tells the developer a lot.
Practice Print the first line of traceback.format_exc
Start with import traceback. In a try block call x = 1 / 0. In except ZeroDivisionError: get the stack trace with tb = traceback.format_exc(). Print the first line with print(tb.splitlines()[0]). The first line is "Traceback (most recent call last):".
Starter code
# Import the traceback module
# Try a division by zero in a try block
# Catch ZeroDivisionError, get the trace
# Print the first lineSample solution
import traceback
# Call 1 / 0 in a try block
try:
x = 1 / 0
# In except ZeroDivisionError: get the trace with format_exc
except ZeroDivisionError:
tb = traceback.format_exc()
# Print the first line
print(tb.splitlines()[0])Expected output
Traceback (most recent call last):
Reading a stack trace
A stack trace has three parts: the header (Traceback (most recent call last):), the call frames (file name, line, code) and the final line with the error type and message. The bottom line tells the actual error.
Frames show calls from top to bottom in aging order; the bottom frame is where the error happened. When debugging you start at the bottom and go up; this makes finding the source easier.
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What does traceback.format_exc() return?
- Only the line number that raised
- Only the error type
- The error stack trace as a string Correct answer
- A file object
Explanation: The string contains file, line and type info.
2 Complete the format_exc call
import traceback
tb = traceback.____()
import traceback
tb = traceback.format_exc()
Explanation: format_exc returns the stack trace as a string.
3 Match the traceback concepts
| Term | Meaning |
|---|---|
format_exc |
Returns the trace as a string |
import traceback |
Imports the module |
splitlines |
Splits into lines |
ZeroDivisionError |
Division by zero error |