The best way to print an exception in Python is to use print(Exception as e). It is simple to debug and print custom error messages. It is clean and concise.
try:
x = 1 / 0
except Exception as e:
print("Error occurred:", e)
# Output: Error occurred: division by zero
Since you cannot divide by 0, it throws a division-by-zero exception, and we print it to the console.
Using the traceback Module
The traceback module is the most detailed and widely used method for debugging. It shows line numbers and the call stack and provides a unique way to print exactly what Python would print when the program crashes.
import traceback
try:
x = undefined_var
except Exception as e:
traceback.print_exc()
# Output: NameError: name 'undefined_var' is not defined
Using traceback.format_exc()
What if you want to control when the exception is printed? That’s where traceback.format_exc() function.
import traceback
try:
[1, 2][5]
except Exception:
error_str = traceback.format_exc()
print("LOG ERROR:\n", error_str)
# Output:
# LOG ERROR:
# Traceback (most recent call last):
# File "/Users/krunallathiya/Desktop/Code/pythonenv/env/app.py", line 4, in <module>
# [1, 2][5]
# IndexError: list index out of range
This approach is helpful when you want to save the traceback or send it somewhere.
Printing custom exception messages
For more detailed information about the error, you can also print the type of the exception along with its message using the print(type()) method.
It is the best way to check the error category programmatically. It helps differentiate error types.
try:
int("krunal")
except Exception as e:
print("Exception Type:", type(e).__name__)
print("Exception Message:", e)
# Output:
# Exception Type: ValueError
# Exception Message: invalid literal for int() with base 10: 'krunal'
Using logging.exception()
What if you want to print the errors on the production application? In that case, it is not a good approach to log the errors on the console. The best approach is to log the errors in a file, then read and analyze it to fix them.
To solve this problem, you can use the built-in logging module and use its .exception() method. It automatically captures the traceback and only works inside an except block.
import logging
logging.basicConfig(level=logging.ERROR)
try:
11 / 0
except Exception:
logging.exception("Something went wrong")
# Output:
# ERROR:root:Something went wrong
# Traceback (most recent call last):
# File "/pythonenv/env/app.py", line 6, in <module>
# 11 / 0
# ZeroDivisionError: division by zero
Using sys.exc_info() (LOW-LEVEL details)
For advanced-level error inspection, use the built-in sys.exc_info() function. It returns low-level error details. It returns a tuple (type, value, traceback object).
The main advantage of the sys.exc_info() method is that it returns raw objects rather than just strings.
import sys
try:
x = [11, 21][18]
except:
exc_type, exc_value, exc_tb = sys.exc_info()
print("Type:", exc_type)
print("Value:", exc_value)
print("Traceback object:", exc_tb)
# Output:
# Type: <class 'IndexError'>
# Value: list index out of range
# Traceback object: <traceback object at 0x104397e80>
That’s all!
