W3docs

How do I print an exception in Python?

You can print an exception in Python by using the print() function and passing the exc variable which is the default variable name for an exception.

You can print an exception in Python by using the print() function and passing the exc variable which is the default variable name for an exception.

For example:

Print an exception in Python

try:
    i = j # j is not defined
except Exception as exc:
    print(exc)

<div class="alert alert-info flex not-prose"> Watch a course <span class="hidden md:block">Watch a video course </span> Python - The Practical Guide</div>

You can also use the traceback module to print a more detailed traceback of the exception.

Print an exception with more details using the traceback module in Python

import traceback
try:
    # some code that might raise an exception
except Exception:
    traceback.print_exc()

You can also use traceback.print_tb(e.__traceback__) to print the traceback of a specific exception instance.

Print the traceback of a specific exception instance in Python

import traceback
try:
    # some code that might raise an exception
except Exception as e:
    traceback.print_tb(e.__traceback__)