Which key failed in Python KeyError?

Take the current exception (I used it as e in this case); then for a KeyError the first argument is the key that raised the exception. Therefore we can do:

except KeyError as e:  # One would do it as 'KeyError, e:' in Python 2.
    cause = e.args[0]

With that, you have the offending key stored in cause.

Expanding your sample code, your log might look like this:

def poijson2xml(location_node, POI_JSON):
  try:
    man_json = POI_JSON["FastestMan"]
    woman_json = POI_JSON["FastestWoman"]
  except KeyError as e:
    LogErrorMessage ("POIJSON2XML", "Can't find mandatory key '"
    e.args[0]
    "' in JSON")

It should be noted that e.message works in Python 2 but not Python 3, so it shouldn’t be used.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)