Skip to content

Python exception stack trace to string

Use traceback.format_exc() to exception stack trace to string in Python. it can handle exceptions caught anywhere.

Python exception stack trace to string example

Simple example code.

import traceback

try:
raise ValueError
except ValueError:
tb = traceback.format_exc()
else:
tb = "No error"
finally:
print(tb)

Output:

Python exception stack trace to string

How to get a stack trace string without raising an exception in Python?

Answer: It’s traceback.extract_stack() if you want convenient access to module and function names and line numbers, or ''.join(traceback.format_stack()) if you just want a string that looks like the traceback.print_stack() output.

Do comment if you have any doubts or suggestions on this Python stack trace 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.

Leave a Reply

Your email address will not be published. Required fields are marked *