How can I determine the invalid key when handling a KeyError exception?



When writing an exception handler for a KeyError, is it possible to know the key that was invalid?


Yes, the invalid key can be determined from the KeyError exception. The KeyError class has variables which can be examined for the key, but the simplest method is to use the str() function to convert the KeyError into a string which will contain the key. The following example shows an attempt to access a key not in the dictionary resulting in an exception.

population = {"California": {"Los Angeles": 3971883,
                             "San Diego": 1394928,
                             "San Jose": 1026908},
              "Texas": {"Houston": 2296224,
                        "San Antonio": 1469845}

    utah_list = population['Utah']

except KeyError as k:
    print("Key " + str(k) + " does not exist")
# Key 'Utah' does not exist