Python: Print Exception Stack trace like Java


If you want to print an exception stack trace in Python like the way it's done in other programming languages such as Java, you can make use of the traceback module.


The traceback module provides a standard interface to extract, format and print stack traces of Python programs.


Read more: https://docs.python.org/3/library/traceback.html


Example:
import traceback

try:
    sum = 1/0
except Exception as e:
    traceback.print_exc()
Output:
Traceback (most recent call last):
  File "<ipython-input-7-33e8636468b8>", line 4, in <cell line: 3>
    sum = 1/0
ZeroDivisionError: division by zero

You get details like the line number, the exact line, the exception type, and the exception description, printed on the console.

Facing issues? Have Questions? Post them here! I am happy to answer!

Author Info:

Rakesh (He/Him) has over 14+ years of experience in Web and Application development. He is the author of insightful How-To articles for Code2care.

Follow him on: X

You can also reach out to him via e-mail: rakesh@code2care.org

Copyright ยฉ Code2care 2024 | Privacy Policy | About Us | Contact Us | Sitemap