Which key failed in Python KeyError?

PythonPython 3.x

Python Problem Overview


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")

Python Solutions


Solution 1 - Python

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.

Solution 2 - Python

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.

Solution 3 - Python

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")

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionQuestionCView Question on Stackoverflow
Solution 1 - Pythonanon582847382View Answer on Stackoverflow
Solution 2 - Pythonuser890167View Answer on Stackoverflow
Solution 3 - PythonjshanleyView Answer on Stackoverflow