Which key failed in Python KeyError?

Question:

If I catch a KeyError, how can I tell what lookup failed?

def poijson2xml(location_node, POI_JSON):
  try:
    man_json = POI_JSON["FastestMan"]
    woman_json = POI_JSON["FastestWoman"]
  except KeyError:
    # How can I tell what key ("FastestMan" or "FastestWoman") caused the error?
    LogErrorMessage ("POIJSON2XML", "Can't find mandatory key in JSON")
Asked By: QuestionC

||

Answers:

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.

Answered By: anon582847382

If you import the sys module you can get exception info with sys.exc_info()

like this:

def POIJSON2DOM (location_node, POI_JSON):
  try:
    man_JSON = POI_JSON["FastestMan"]
    woman_JSON = POI_JSON["FastestWoman"]

  except KeyError:

    # you can inspect these variables for error information
    err_type, err_value, err_traceback = sys.exc_info()

    REDI.LogErrorMessage ("POIJSON2DOM", "Can't find mandatory key in JSON")
Answered By: jshanley

Not sure if you’re using any modules to assist you – if the JSON is coming in as a dict, one can use dict.get() towards a useful end.

def POIJSON2DOM (location_node, POI_JSON):
    man_JSON = POI_JSON.get("FastestMan", 'No Data for fastest man')
    woman_JSON = POI_JSON.get("FastestWoman", 'No Data  for fastest woman')
    #work with the answers as you see fit

dict.get() takes two arguments – the first being the key you want, the second being the value to return if that key does not exist.

Answered By: user890167
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.