Beginning Python - From Novice to Professional

Beginning Python - From Novice to Professional Beginning Python - From Novice to Professional

16.01.2014 Views

CHAPTER 8 ■ ■ ■ Exceptions When writing computer programs, it is usually possible to discern between a normal course of events and something that’s exceptional (out of the ordinary). Such exceptional events might be errors (such as trying to divide a number by zero), or simply something you might not expect to happen very often. To handle such exceptional events, you might use conditionals everywhere the events might occur (for example, have your program check whether the denominator is zero for every division). However, this would not only be inefficient and inflexible, but would also make the programs illegible. You might be tempted to ignore these exceptions and just hope they won’t occur, but Python offers a powerful alternative. What Is an Exception? To represent exceptional conditions, Python uses exception objects. If such an exception object is not handled in any way, the program terminates with a so-called traceback (an error message): >>> 1/0 Traceback (most recent call last): File "", line 1, in ? ZeroDivisionError: integer division or modulo by zero If such error messages were all you could use exceptions for, exceptions wouldn’t be very interesting. The fact is, however, that each exception is an instance of some class (in this case ZeroDivisionError), and these instances may be raised and caught in various ways, allowing you to trap the error and do something about it instead of allowing the entire program to fail. In the next section, you learn how to create and raise your own exceptions. In the following sections, you learn about handling exceptions in various ways. WARNINGS Exceptions may be used to represent exceptional or illegal states in your program (such as trying to divide a number by zero, or reading from a nonexistent file), and will, unless caught by you, terminate the program. Warnings, on the other hand, are mild error messages; they notify you that something isn’t quite right, but your program keeps running. For example, try to import the regex module: Continued 159

160 CHAPTER 8 ■ EXCEPTIONS >>> import regex __main__:1: DeprecationWarning: the regex module is deprecated; please use the re module >>> regex It’s obvious that the interpreter didn’t like this; the regex module is old, and you should use the re module instead. (You learn more about the re module in Chapter 10.) However, because a lot of code already uses the regex module, it would be unreasonable to demand that re be used; that would simply break all the older code. So instead, a warning is issued. If, for some reason, you are stuck with the regex module, you can happily ignore the warning (although you probably should rewrite your code). You can even filter it out (with the function filterwarnings), so it isn’t printed: >>> from warnings import filterwarnings >>> filterwarnings('ignore') >>> import regex If you want to learn more about warnings, you can check out the warnings module in the standard library documentation at http://www.python.org/doc/lib. Making Things Go Wrong . . . Your Way As you’ve seen, exceptions are raised automatically when something is wrong. Before looking at how to deal with those exceptions, let’s take a look at how you can raise exceptions yourself— and even create your own kinds of exceptions. The raise Statement To raise an exception, you use the raise statement with an argument that is either a class or an instance. When using a class, an instance is created automatically; you can optionally provide a string argument after the class, separated by a comma. Here are some simple examples, using the built-in exception class Exception: >>> raise Exception Traceback (most recent call last): File "", line 1, in ? Exception >>> raise Exception, 'hyperdrive overload' Traceback (most recent call last): File "", line 1, in ? Exception: hyperdrive overload >>> raise Exception('hyperdrive overload') Traceback (most recent call last): File "", line 1, in ? Exception: hyperdrive overload

160 CHAPTER 8 ■ EXCEPTIONS<br />

>>> import regex<br />

__main__:1: DeprecationWarning: the regex module is deprecated;<br />

please use the re module<br />

>>> regex<br />

<br />

It’s obvious that the interpreter didn’t like this; the regex module is old, and you should use the re module<br />

instead. (You learn more about the re module in Chapter 10.) However, because a lot of code already uses the<br />

regex module, it would be unreasonable <strong>to</strong> demand that re be used; that would simply break all the older<br />

code. So instead, a warning is issued.<br />

If, for some reason, you are stuck with the regex module, you can happily ignore the warning (although<br />

you probably should rewrite your code). You can even filter it out (with the function filterwarnings), so it<br />

isn’t printed:<br />

>>> from warnings import filterwarnings<br />

>>> filterwarnings('ignore')<br />

>>> import regex<br />

If you want <strong>to</strong> learn more about warnings, you can check out the warnings module in the standard<br />

library documentation at http://www.python.org/doc/lib.<br />

Making Things Go Wrong . . . Your Way<br />

As you’ve seen, exceptions are raised au<strong>to</strong>matically when something is wrong. Before looking<br />

at how <strong>to</strong> deal with those exceptions, let’s take a look at how you can raise exceptions yourself—<br />

and even create your own kinds of exceptions.<br />

The raise Statement<br />

To raise an exception, you use the raise statement with an argument that is either a class or an<br />

instance. When using a class, an instance is created au<strong>to</strong>matically; you can optionally provide<br />

a string argument after the class, separated by a comma. Here are some simple examples, using<br />

the built-in exception class Exception:<br />

>>> raise Exception<br />

Traceback (most recent call last):<br />

File "", line 1, in ?<br />

Exception<br />

>>> raise Exception, 'hyperdrive overload'<br />

Traceback (most recent call last):<br />

File "", line 1, in ?<br />

Exception: hyperdrive overload<br />

>>> raise Exception('hyperdrive overload')<br />

Traceback (most recent call last):<br />

File "", line 1, in ?<br />

Exception: hyperdrive overload

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!