Practical examples of exception handling

suggest change

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:

while True:
    try:
        nb = int(input('Enter a number: '))
        break
    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.

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.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:


Exceptions:
* Else
* Practical examples of exception handling

Table Of Contents
2 Filter
3 List
7 Loops
22 Reduce
27 Classes
31 Set
42 Tuple
45 Enum
62 Sockets
70 Exceptions
89 urllib
92 Idioms
104 Stack
105 Profiling
109 Logging
111 os module
118 Mixins
120 ArcPy
126 Arrays
132 2to3 tool
135 Unicode
138 Neo4j
140 Curses
141 Templates
145 heapq
146 tkinter
154 Audio
155 pyglet
157 ijson
160 Flask
161 Groupby
163 pygame
165 hashlib
166 Gzip
167 ctypes
185 pyaudio
186 shelve