user3685952
user3685952

Reputation: 75

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 ?

Upvotes: 1

Views: 2827

Answers (2)

heckman
heckman

Reputation: 46

If you replace str(e) with repr(e) Python 2 will produce KeyError(1,) and Python 3 will produce KeyError(1)

This doesn't quite produce your desired output, but it may be close enough?

Upvotes: 0

gcarvelli
gcarvelli

Reputation: 1580

Instead of this:

print str(e)

do this:

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

or just this:

print(type(e).__name__, e)

Upvotes: 3

Related Questions