How to Print an Exception in Python?

In python you can print exceptions using try-except blocks to capture and display error messages, stack traces or debug information during runtime.

Printing exceptions in python helps to debug issues by giving clear information about what went wrong and where. You can access the exception message or full traceback using built-in methods and modules. 

Method 1: Basic Exception Message

Print a simple error message by using except Exception as e.

python
try:    result = 10 / 0 except Exception as e:     print("Exception occurred:", e)
This is staples way to print an exception message.

Method 2: Using traceback Module

Use the traceback module for detailed error logs.

python
import traceback try:     x = [1, 2, 3]     print(x[5]) except Exception:     traceback.print_exc()
This prints the full call stack leading up to the error which is great for debugging larger applications. 
Also Read: Top 25 Python Performance Tips for Scalable Applications

Method 3: Catch Specific Exceptions

Catch specific errors and handle them differently.

python
try:    int("abc") except ValueError as e:     print("Caught ValueError:", e)
Helps you control flow based on error types. 

Method 4: Use Logging Instead of Print (Recommended for Production)

Log exceptions for persistent tracking and debugging.

python
import logging logging.basicConfig(level=logging.ERROR)  try:     open("missing_file.txt") except Exception as e:     logging.exception("File open failed")
Writes the exception info to logs including traceback which is safer and cleaner than print. 

Tip

  • Use traceback.print_exc() for detailed error reports. 
  • Catch specific exceptions to avoid hiding bugs. 
  • Use logging in real-world applications to persist and organize exception reports.
Related

Python string does not have a built-in .contains() method like some other languages (e.g., Java), but you can easily check if a substring exists using…

10 Oct, 2025

These are the typical reasons why the conda command fails and practical steps to fix them across Windows, macOS and Linux environments. Here are some…

07 Oct, 2025

Hiring Python developers in the USA has become a top priority for companies building complex applications in finance, healthcare, e-commerce and enterprise technology. Companies are…

03 Oct, 2025
Request a Quote Schedule a Meeting