Skip to content

Python print exception type

  • by

There are different ways to get the print exception type in Python. If you want to print the name of the exception in an error message use anyone the below methods.

  1. type(exception).__name__
  2. exception.__class__.__name__
  3. exception.__class__.__qualname__
try:
    foo = bar
except Exception as exception:
    assert type(exception).__name__ == 'NameError'
    assert exception.__class__.__name__ == 'NameError'
    assert exception.__class__.__qualname__ == 'NameError'

Python print exception type

Simple example codes determine what type of exception occurred.

try:
x = 1 / 0
except Exception as ex:
template = "An exception of type {0} occurred. Arguments:\n{1!r}"
message = template.format(type(ex).__name__, ex.args)
print(message)

Output:

Python print exception type

If you also want the same stack trace can get that like this.

import traceback
print traceback.format_exc()

If you use the logging module, you can print the exception to the log (along with a message) like this:

import logging
log = logging.getLogger()
log.exception("Message for you, sir!")

If you want to dig deeper and examine the stack, look at variables, etc., use the post_mortem function of the pdb module inside the except block:

import pdb
pdb.post_mortem()

Source: https://stackoverflow.com/questions/9823936/

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

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading