04.08.2014 Views

o_18ufhmfmq19t513t3lgmn5l1qa8a.pdf

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

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 to 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 to 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 automatically when something is wrong. Before looking<br />

at how to 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 automatically; 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!