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
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.