Search code examples
pythonexceptionkeyerror

how to get the key information from a KeyError


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?


Solution

  • 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