← Go Back

How to Store an Exception in a Variable or File

The traceback standard module allows you to obtain information about the last exception that occurred in a program. For example, consider the following error.

>>> int("Hello world!")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: 'Hello world!'

To save the entire error message in a variable, you must first capture the exception using a try/except clause and then retrieve the full traceback with format_exc().

from traceback import format_exc

try:
int("Hello world!")
except ValueError:
exc = format_exc()
print(exc)

Thus, when the exception gets raised, the error message is stored as a string in exc.

On the other hand, to save the content of the exception to a file, print_exc() is used.

from traceback import print_exc

try:
int("Hello world!")
except ValueError:
with open("error.log", "w") as f:
print_exc(file=f)

exceptions traceback files


🐍 You might also find interesting: