Using the print_exc() method or print_exception() method you can Print Traceback in Python. The module defines the following functions:
- traceback.print_exc(limit=None, file=None, chain=True)
- traceback.print_exception(etype, value, tb, limit=None, file=None, chain=True)
Read more: https://docs.python.org/3/library/traceback.html
Python Print Traceback
Simple example code printing the stack trace to handle the exception generated.
Using print_exc() method.
import traceback
A = [1, 2, 3, 4]
try:
value = A[5]
except:
# printing stack trace
traceback.print_exc()
Output:
Using print_exception() method
import traceback
import sys
a = 1
b = 0
try:
value = a / b
except:
# printing stack trace
traceback.print_exception(*sys.exc_info())
Output:
Traceback (most recent call last):
File "C:\Users\Rohit\PycharmProjects\pythonProject\modules\main.py", line 8, in <module>
value = a / b
ZeroDivisionError: division by zero
How to catch and print the full exception traceback without halting/exiting the program?
Answer: traceback.format_exc()
or sys.exc_info()
will yield more info
import traceback
import sys
try:
x = 1/0
except Exception:
print(traceback.format_exc())
# or
print(sys.exc_info()[2])
Do comment if you have any doubts or suggestions on this Python Traceback topic.
Note: IDE: PyCharm 2021.3.3 (Community Edition)
Windows 10
Python 3.10.1
All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.