How to Print Exception Stack Trace in Python
Last Updated :
07 Apr, 2025
In Python, when an exception occurs, a stack trace provides details about the error, including the function call sequence, exact line and exception type. This helps in debugging and identifying issues quickly.
Key Elements of a Stack Trace:
- Traceback of the most recent call
- Location in the program
- Line where the error occurred
- Exception type and message
Let's explore different methods to achieve this.
Using traceback.print_exec()
traceback.print_exc() is a simple way to print the full exception stack trace directly to the console. It is useful when debugging code interactively or logging errors in basic scripts. It automatically captures the latest exception and prints its traceback without requiring extra parameters.
Example:
Python
import traceback
try:
1 / 0 # division by zero
except Exception:
traceback.print_exc()
Output:
Traceback (most recent call last):
File "/home/guest/sandbox/Solution.py", line 4, in <module>
1 / 0 # division by zero
~~^~~
ZeroDivisionError: division by zero
Explanation: This code attempts to divide by zero inside a try block, which raises a ZeroDivisionError. The except block catches the exception and prints the detailed error traceback using traceback.print_exc(), helping in debugging by displaying where the error occurred.
traceback.format_exc() captures the stack trace as a string, making it useful for logging or displaying errors in custom formats. Instead of printing directly, it allows further processing, such as storing errors in logs or sending them in reports. This method provides flexibility while maintaining detailed traceback information.
Example:
Python
import traceback
try:
1 / 0 # division by zero
except Exception:
error_msg = traceback.format_exc()
print(error_msg)
Output:
Traceback (most recent call last):
File "/home/guest/sandbox/Solution.py", line 4, in <module>
1 / 0 # division by zero
~~^~~
ZeroDivisionError: division by zero
Explanation: The except block catches the exception and uses traceback.format_exc() to capture the complete error traceback as a string. This error message is then stored in error_msg and printed, providing detailed debugging information about where the error occurred.
Using logging module
logging module's logging.exception() method logs the error message along with the full stack trace, making it ideal for production environments. It ensures structured error logging with different severity levels and supports writing errors to log files, making debugging and monitoring easier.
Example:
Python
import logging
logging.basicConfig(level=logging.ERROR) # Set logging level
try:
1 / 0 # division by zero
except Exception:
logging.exception("An error occurred:")
Output:
ERROR:root:An error occurred:
Traceback (most recent call last):
File "/home/guest/sandbox/Solution.py", line 6, in <module>
1 / 0 # division by zero
~~^~~
ZeroDivisionError: division by zero
Explanation: except block catches the exception and uses logging.exception() to log the error message along with the complete traceback. The logging.basicConfig(level=logging.ERROR) sets the logging level to ERROR, ensuring that only error messages and above are logged.
Using sys.exc_info()
sys.exc_info() provides detailed control over exception handling by returning a tuple containing the exception type, value and traceback. It is useful for advanced debugging, custom error handling, or re-raising exceptions while maintaining full traceback details.
Example:
Python
import sys
import traceback
try:
1 / 0 # division by zero
except Exception:
exc_type, exc_val, exc_tb = sys.exc_info()
traceback.print_exception(exc_type, exc_val, exc_tb)
Output:
Traceback (most recent call last):
File "/home/guest/sandbox/Solution.py", line 5, in <module>
1 / 0 # division by zero
~~^~~
ZeroDivisionError: division by zero
Explanation: except block catches the exception and retrieves detailed exception information using sys.exc_info(), which returns a tuple containing the exception type, value and traceback object. These details are then passed to traceback.print_exception(), which prints the full error traceback.
Similar Reads
How to print the Python Exception/Error Hierarchy? Before Printing the Error Hierarchy let's understand what an Exception really is? Exceptions occur even if our code is syntactically correct, however, while executing they throw an error. They are not unconditionally fatal, errors which we get while executing are called Exceptions. There are many Bu
3 min read
Python Print Exception In Python, exceptions are errors that occur at runtime and can crash your program if not handled. While catching exceptions is important, printing them helps us understand what went wrong and where. In this article, we'll focus on different ways to print exceptions.Using as keywordas keyword lets us
3 min read
How to pass argument to an Exception in Python? There might arise a situation where there is a need for additional information from an exception raised by Python. Python has two types of exceptions namely, Built-In Exceptions and User-Defined Exceptions.Why use Argument in Exceptions? Using arguments for Exceptions in Python is useful for the fol
2 min read
How to print to stderr and stdout in Python? In Python, whenever we use print() the text is written to Pythonâs sys.stdout, whenever input() is used, it comes from sys.stdin, and whenever exceptions occur it is written to sys.stderr. We can redirect the output of our code to a file other than stdout. But you may be wondering why one should do
3 min read
How To Fix Valueerror Exceptions In Python Python comes with built-in exceptions that are raised when common errors occur. These predefined exceptions provide an advantage because you can use the try-except block in Python to handle them beforehand. For instance, you can utilize the try-except block to manage the ValueError exception in Pyth
4 min read