How to get python default exception message in exception handling

Tags: ,



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 ?

Answer

Instead of this:

print str(e)

do this:

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

or just this:

print(type(e).__name__, e)


Source: stackoverflow