The General Solution: try
except
As with any exception, you can always use the try
except
block to isolate the potential exception-raising code and provide a backup solution.
You can use the try
except
block in a similar example as before, but this time providing a default message to be printed should a KeyError
be raised in the normal case:
1# ages.py
2
3ages = {'Jim': 30, 'Pam': 28, 'Kevin': 33}
4person = input('Get age for: ')
5
6try:
7 print(f'{person} is {ages[person]} years old.')
8except KeyError:
9 print(f"{person}'s age is unknown.")
https://realpython.com/python-keyerror/