Skip to content
Advertisement

How to get python default exception message in exception handling

When I handle an exception in python

try:
    a = dict()
    a[1]
except Exception as e:
    print str(e)

It prints

1

I expect it to print

KeyError: 1

Is there a way to retrieve the default error message ?

Advertisement

Answer

Instead of this:

print str(e)

do this:

print(type(e).__name__ + ": " + str(e))

or just this:

print(type(e).__name__, e)
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement