1

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 ?

3
  • This code doesn't return anything, only prints, and second, no exception is raised... Commented Nov 22, 2014 at 4:16
  • 1
    Best to not catch generic Exceptions and expect good things to happen. The point of exceptions is that they give you a specific issue to deal with - catching the base case means you don't know what you're handling, so how can you handle it correctly? Commented Nov 22, 2014 at 4:18
  • Most of the times, I can't catch all errors and exceptions, so if I want to exit the program gracefully I need to catch generic Exceptions Commented Nov 22, 2014 at 7:19

2 Answers 2

3

Instead of this:

print str(e)

do this:

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

or just this:

print(type(e).__name__, e)
Sign up to request clarification or add additional context in comments.

Comments

0

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?

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.