5.1 traceback
Module
Stack trace (traceback)
is info that shows the sequence of function calls that led to an exception. It's a crucial tool for debugging because it helps devs figure out where and why an error occurred.
Analyzing the stack trace (traceback)
is a key part of debugging programs, helping developers understand where and why an error happened. Python gives us the traceback
module, which has functions for handling stack traces. This module lets you extract, format, and print stack trace info.
Getting and Working with the Stack Trace
To work with a stack trace, you need to import the traceback
module, which provides functions for formatting and printing stack trace info.
Example of getting and printing a stack trace:
import traceback
def function_c():
return 1 / 0 # This will raise ZeroDivisionError
def function_b():
function_c()
def function_a():
try:
function_b()
except ZeroDivisionError as e:
print("An exception occurred:")
traceback.print_exc() # Prints the stack trace
function_a()
Output:
An exception occurred:
Traceback (most recent call last):
File "example.py", line 12, in function_a
function_b()
File "example.py", line 8, in function_b
function_c()
File "example.py", line 4, in function_c
return 1 / 0
ZeroDivisionError: division by zero
Function traceback.print_exc()
This function prints the stack trace for the current exception to the standard error stream.
Example:
try:
1 / 0
except ZeroDivisionError:
traceback.print_exc()
Function traceback.format_exc()
This function returns a string with the formatted stack trace of the current exception.
try:
1 / 0
except ZeroDivisionError:
error_message = traceback.format_exc()
print("Stack trace as a string:")
print(error_message)
Function traceback.extract_tb(tb)
This function extracts "raw" stack trace details from a traceback object
, which you can get via sys.exc_info()
. It returns a list of stack frames.
5.2 Handling and Analyzing the Stack Trace
Function traceback.format_tb(tb)
This function returns a formatted list of strings representing the stack trace.
import sys
import traceback
def function_c():
return 1 / 0 # This will raise ZeroDivisionError
def function_b():
function_c()
def function_a():
try:
function_b()
except ZeroDivisionError:
tb = sys.exc_info()[2]
formatted_tb = traceback.format_tb(tb)
print("Formatted stack trace:")
for line in formatted_tb:
print(line, end="")
function_a()
Function traceback.format_exception(exc_type, exc_value, exc_tb)
This function returns a full formatted list of strings representing the exception and the stack trace.
import sys
import traceback
def function_c():
return 1 / 0 # This will raise ZeroDivisionError
def function_b():
function_c()
def function_a():
try:
function_b()
except ZeroDivisionError as e:
exc_type, exc_value, exc_tb = sys.exc_info()
full_tb = traceback.format_exception(exc_type, exc_value, exc_tb)
print("Full formatted stack trace:")
for line in full_tb:
print(line, end="")
function_a()
Sometimes it's helpful to break down each stack frame in detail to get specific info on where the exception happened and the context of that location.
import traceback
import sys
def function_c():
return 1 / 0 # This will raise ZeroDivisionError
def function_b():
function_c()
def function_a():
try:
function_b()
except ZeroDivisionError:
tb = sys.exc_info()[2]
for frame in traceback.extract_tb(tb):
print(f"File: {frame.filename}")
print(f"Line: {frame.lineno}")
print(f"Function Name: {frame.name}")
print(f"Code: {frame.line}")
print("-" * 40)
function_a()
5.3 Using traceback
for Logging
Sometimes it's important to save stack trace info in a log file for further analysis. You can do this using functions from the traceback
module and the standard logging
module.
Example:
import logging
import traceback
import sys
logging.basicConfig(filename='error.log', level=logging.ERROR)
def function_c():
return 1 / 0 # This will raise ZeroDivisionError
def function_b():
function_c()
def function_a():
try:
function_b()
except ZeroDivisionError as e:
exc_type, exc_value, exc_tb = sys.exc_info()
full_tb = traceback.format_exception(exc_type, exc_value, exc_tb)
logging.error("An exception occurred:\n%s", ''.join(full_tb))
function_a()
We'll cover logging a bit later, but I hope this info was helpful for you.
GO TO FULL VERSION