pythonexception

How to get the name of an exception that was caught in Python?


How can I get the name of an exception that was raised in Python?

e.g.,

try:
    foo = bar
except Exception as exception:
    name_of_exception = ???
    assert name_of_exception == 'NameError'
    print "Failed with exception [%s]" % name_of_exception

For example, I am catching multiple (or all) exceptions, and want to print the name of the exception in an error message.


Solution

  • Here are a few different ways to get the name of the class of the exception:

    1. type(exception).__name__
    2. exception.__class__.__name__
    3. exception.__class__.__qualname__

    e.g.,

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