2

Is there a way to get the key that raised a KeyError?

or in general, where can I find (if available) properties of an Exception?

2 Answers 2

8

Exceptions have a .args attribute which is a tuple; for a KeyError exception that tuple contains the key that triggered the exception:

>>> try:
...     {}['foo']
... except KeyError as ex:
...     print(ex.args[0])
... 
foo
1

Script:

d = dict(a=1)
try:
    d['b']
except KeyError as e:
    print e

Output:

'b'

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.