Reputation: 75
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
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
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