Question or problem about Python programming:
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")
How to solve the problem:
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
With that, you have the offending key stored in
It should be noted that
e.message works in Python 2 but not Python 3, so it shouldn’t be used.
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.
If you import the
sys module you can get exception info with
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")