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

Question

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

Answer

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}
              }

try:
    utah_list = population['Utah']

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

when i tried this syntax i got a type error at “as”, like i couldnt aliasite KeyError as k, why that happens?

1 Like

Hei, @poncianodavid! I’m sorry you got that! For me it worked and the code got executed. Maybe you had some white space. I know this doesn’t help much. However, try again! I’m sure you’ll figure it out (of you haven’t already :slight_smile: )

What is “as”? I have never seen this syntax

It is what it sounds like. The value of KeyError is substituted to temporary variable k.

1 Like

why does it have to be converted to a string? what’s the original type and how does this conversion work?

You convert the KeyError to a string, so it could print that the key you requested for (in the example above, its “Utah”) doesn’t exist. If you change the value for k variable (for instance, “Moscow”, you will get: Key “Moscow” doesn’t exist".

I hope I was able to answer your question. Cheers