Python Language Exceptions Practical examples of exception handling


User 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:

Python 3.x3.0
while True:
        nb = int(input('Enter a number: '))
    except ValueError:
        print('This is not a number, try again.')

Note: Python 2.x would use raw_input instead; the function input exists in Python 2.x but has different semantics. In the above example, input would also accept expressions such as 2 + 2 which evaluate to a number.

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.


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)):
       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.