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.

CHAPTER 8 ■ EXCEPTIONS 161<br />

■Note There are actually two other ways to use raise. The argument may be a string, or you can call<br />

raise without any arguments. Using a string argument is considered obsolete; calling raise without arguments<br />

is covered in the section “Look, Ma, No Arguments!” later in this chapter.<br />

The first example (raise Exception) raises a generic exception with no information of<br />

what went wrong. In the last two examples, I added the error message hyperdrive overload. As<br />

you can see, the two forms raise class, message and raise class(message) are equivalent; both<br />

raise an exception with the given error message.<br />

There are many built-in classes available. You can find a description of all of them in the<br />

Python Library Reference, in the section “Built-in Exceptions.” You can also explore them<br />

yourself with the interactive interpreter; they are all found in the module exceptions, for your<br />

convenience (as well as in the built-in namespace). To list the contents of a module, you can<br />

use the dir function, which is described in Chapter 10:<br />

>>> import exceptions<br />

>>> dir(exceptions)<br />

['ArithmeticError', 'AssertionError', 'AttributeError', ...]<br />

In your interpreter, this list will be quite a lot longer—I’ve deleted most of the names in the<br />

interest of legibility. All of these exceptions can be used in your raise statements:<br />

>>> raise ArithmeticError<br />

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

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

ArithmeticError<br />

Table 8-1 describes some of the most important built-in exceptions.<br />

Table 8-1. Some Built-in Exceptions<br />

Class Name<br />

Exception<br />

AttributeError<br />

IOError<br />

IndexError<br />

KeyError<br />

NameError<br />

SyntaxError<br />

TypeError<br />

ValueError<br />

ZeroDivisionError<br />

Description<br />

The root class for all exceptions<br />

Raised when attribute reference or assignment fails<br />

Raised when trying to open a nonexistent file (among other things)<br />

Raised when using a nonexistent index on a sequence<br />

Raised when using a nonexistent key on a mapping<br />

Raised when a name (variable) is not found<br />

Raised when the code is ill-formed<br />

Raised when a built-in operation or function is applied to an object of<br />

the wrong type<br />

Raised when a built-in operation or function is applied to an object<br />

with correct type, but with an inappropriate value<br />

Raised when the second argument of a division or modulo operation<br />

is zero

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

Saved successfully!

Ooh no, something went wrong!