Question 7.10: Handling Exceptions If something goes wrong while a program ......

Handling Exceptions

If something goes wrong while a program is running, you want to catch the error or exception and display a more user-friendly error message.

Step-by-Step
The 'Blue Check Mark' means that this solution was answered by an expert.
Learn more on how do we answer questions.

Use Python’s try/except construct.

The following example, taken from Recipe 7.7, catches any problems in opening a file:

try:
f = open(‘test.txt’)
s = f.read()
f.close()
except IOError:
print(“Cannot open the file”)

Discussion

A common situation where runtime exceptions can occur—in addition to during file access—is when you are accessing a list and the index you are using is outside the bounds of the list. For example, this happens if you try to access the fourth element of a threeelement list:

>>> list = [1, 2, 3]
>>> list[4]
Traceback (most recent call last):
File “<stdin>”, line 1, in <module>
IndexError: list index out of range

Errors and exceptions are arranged in a hierarchy, and you can be as specific or general as you like when catching the exceptions.

Exception is pretty near the top of that tree and will catch almost any exception. You can also have separate except sections for catching different types of exception and handling each in a different way. If you do not specify any exception class, all exceptions will be caught.

Python also allows you to have else and finally clauses in your error handling:

list = [1, 2, 3]
try:
list[8]
except:
print(“out of range”)
else:
print(“in range”)
finally:
print(“always do this”)

The else clause will be run if there is no exception, and the finally clause will be run whether there is an exception or not.

Whenever an exception occurs, you can get more information about it using the exception object, which is available only if you use the as keyword, as shown in the following example:

>>> list = [1, 2, 3]
>>> try:
… list[8]
… except Exception as e:
… print(“out of range”)
… print(e)

out of range
list index out of range
>>>

See Also

Python documentation for Python exception class hierarchy.

Related Answered Questions

Question: 7.14

Verified Answer:

Import sys and use its argv property, as shown in ...
Question: 7.15

Verified Answer:

Python has a library for the Simple Mail Transfer ...
Question: 7.13

Verified Answer:

Python has an extensive library for making HTTP re...
Question: 7.12

Verified Answer:

Use the random library: >>> import ran...
Question: 7.16

Verified Answer:

Use the bottle Python library to run a pure Python...
Question: 7.11

Verified Answer:

Use the import command: import random Discus...
Question: 7.8

Verified Answer:

To read a file’s contents, you need to use the fil...
Question: 7.7

Verified Answer:

Use the open, write, and close functions to open a...
Question: 7.4

Verified Answer:

Define a class and provide it with the member vari...