简体   繁体   中英

Basic exception handling with dictionary

I'm trying a block of code to handle a specific exception:

try:
    my_dict.get(s)

except KeyError:
    print("This key does not exist in the dictionary")
    return None
else:
    print (my_dict.get(s))

return 

So this is a part of a function where 's' is an argument of the function

It works fine and prints the value corresponding to the key when the try block does not throw an exception

But when it does I cant get "This key does not exist in the dictionary" to print and I don't know why. The program simply returns None in the case of a KeyError.

I know that this must be very obvious but I can't work it out and it's frustrating me

Can someone please tell me what's wrong with this block, thanks

dict.get does not raise KeyError , it is safe method. Use my_dict[s] instead if you want to catch exception.

The dict.get method does not raise KeyError . Instead, it returns None by default when the given key is not found in the dict. You should use square brackets instead to access the dict by a key, so that it can raise KeyError when a given key is not found as you intend:

try:
    print(my_dict[s])
except KeyError:
    print("This key does not exist in the dictionary")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM