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.

Summarize with AI

Not enough time? get the key points instantly.

Printing exceptions in Python development 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 Python applications to persist and organize exception reports.

Resources

Insights from our engineering leaders.

Our team shares practical insights on the technologies and engineering decisions shaping enterprise software today, grounded in real client work.

Python

How to Copy Files in Python

You can copy files in python using the shutil module which provides high level file and collection of files operations. You can also combine it…