Python etc / KeyError

Published: 15 April 2021, 18:00

Most of the exceptions raised from the standard library or built-ins have a quite descriptive self-contained message:

try:
  [][0]
except IndexError as e:
  exc = e

exc.args
# ('list index out of range',)

However, KeyError is different: instead of a user-friendly error message it contains the key which is missed:

try:
  {}[0]
except KeyError as e:
  exc = e

exc.args
# (0,)

So, if you log an exception as a string, make sure you save the class name (and the traceback) as well, or at least use repr instead of str:

repr(exc)
# 'KeyError(0)'