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")
What is Python KeyError Exception? Python KeyError is raised when we try to access a key from dict, which doesn't exist. It's one of the built-in exception classes and raised by many modules that work with dict or objects having key-value pairs.
Python: check if dict has key using get() function If given key exists in the dictionary, then it returns the value associated with this key, If given key does not exists in dictionary, then it returns the passed default value argument.
The Python "KeyError: 1" exception is caused when we try to access a 1 key in a a dictionary that doesn't contain the key. To solve the error, set the key in the dictionary before trying to access it or conditionally set it if it doesn't exist.
Using try-except The try-except block is one of the best possible ways to handle the KeyError exceptions. It is also useful where the get() and the if and in operators are not supported. Here, in this example, there are two cases— normal case and a backup case.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With