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