16.01.2014 Views

Beginning Python - From Novice to Professional

Beginning Python - From Novice to Professional

Beginning Python - From Novice to Professional

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

CHAPTER 8<br />

■ ■ ■<br />

Exceptions<br />

When writing computer programs, it is usually possible <strong>to</strong> discern between a normal course<br />

of events and something that’s exceptional (out of the ordinary). Such exceptional events might be<br />

errors (such as trying <strong>to</strong> divide a number by zero), or simply something you might not expect<br />

<strong>to</strong> happen very often. To handle such exceptional events, you might use conditionals everywhere<br />

the events might occur (for example, have your program check whether the denomina<strong>to</strong>r is<br />

zero for every division). However, this would not only be inefficient and inflexible, but would<br />

also make the programs illegible. You might be tempted <strong>to</strong> ignore these exceptions and just<br />

hope they won’t occur, but <strong>Python</strong> offers a powerful alternative.<br />

What Is an Exception?<br />

To represent exceptional conditions, <strong>Python</strong> uses exception objects. If such an exception object<br />

is not handled in any way, the program terminates with a so-called traceback (an error message):<br />

>>> 1/0<br />

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

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

ZeroDivisionError: integer division or modulo by zero<br />

If such error messages were all you could use exceptions for, exceptions wouldn’t be very<br />

interesting. The fact is, however, that each exception is an instance of some class (in this case<br />

ZeroDivisionError), and these instances may be raised and caught in various ways, allowing<br />

you <strong>to</strong> trap the error and do something about it instead of allowing the entire program <strong>to</strong> fail.<br />

In the next section, you learn how <strong>to</strong> create and raise your own exceptions. In the following<br />

sections, you learn about handling exceptions in various ways.<br />

WARNINGS<br />

Exceptions may be used <strong>to</strong> represent exceptional or illegal states in your program (such as trying <strong>to</strong> divide a<br />

number by zero, or reading from a nonexistent file), and will, unless caught by you, terminate the program.<br />

Warnings, on the other hand, are mild error messages; they notify you that something isn’t quite right, but your<br />

program keeps running. For example, try <strong>to</strong> import the regex module:<br />

Continued<br />

159

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

Saved successfully!

Ooh no, something went wrong!