Practical examples of exception handling
suggest changeUser input
Imagine you want a user to enter a number via input. You want to ensure that the input is a number. You can use try/except for this:
while True:
try:
nb = int(input('Enter a number: '))
break
except ValueError:
print('This is not a number, try again.')
If the input could not be converted to an integer, a ValueError is raised. You can catch it with except. If no exception is raised, break jumps out of the loop. After the loop, nb contains an integer.
Dictionaries
Imagine you are iterating over a list of consecutive integers, like range(n), and you have a list of dictionaries d that contains information about things to do when you encounter some particular integers, say skip the d[i] next ones.
d = [{7: 3}, {25: 9}, {38: 5}]
for i in range(len(d)):
do_stuff(i)
try:
dic = d[i]
i += dic[i]
except KeyError:
i += 1
A KeyError will be raised when you try to get a value from a dictionary for a key that doesn’t exist. do_stuff is not defined on this page. This sample does not skip items. The keys in d are 7, 25, and 38, while i is 0, 1, and 2, so dic[i] always raises KeyError. Assigning to i also does not change the values range still has to yield.