Online Book Reader

Home Category

Learning Python - Mark Lutz [459]

By Root 1554 0
RAISED, WITH ELSE

else run

finally run

after run

--------------------------------

EXCEPTION RAISED BUT NOT CAUGHT

finally run

Traceback (most recent call last):

File "mergedexc.py", line 36, in

x = 1 / 0

ZeroDivisionError: int division or modulo by zero

This example uses built-in operations in the main action to trigger exceptions (or not), and it relies on the fact that Python always checks for errors as code is running. The next section shows how to raise exceptions manually instead.

The raise Statement

To trigger exceptions explicitly, you can code raise statements. Their general form is simple—a raise statement consists of the word raise, optionally followed by the class to be raised or an instance of it:

raise # Raise instance of class

raise # Make and raise instance of class

raise # Reraise the most recent exception

As mentioned earlier, exceptions are always instances of classes in Python 2.6 and 3.0. Hence, the first raise form here is the most common—we provide an instance directly, either created before the raise or within the raise statement itself. If we pass a class instead, Python calls the class with no constructor arguments, to create an instance to be raised; this form is equivalent to adding parentheses after the class reference. The last form reraises the most recently raised exception; it’s commonly used in exception handlers to propagate exceptions that have been caught.

To make this clearer, let’s look at some examples. With built-in exceptions, the following two forms are equivalent—both raise an instance of the exception class named, but the first creates the instance implicitly:

raise IndexError # Class (instance created)

raise IndexError() # Instance (created in statement)

We can also create the instance ahead of time—because the raise statement accepts any kind of object reference, the following two examples raise IndexError just like the prior two:

exc = IndexError() # Create instance ahead of time

raise exc

excs = [IndexError, TypeError]

raise excs[0]

When an exception is raised, Python sends the raised instance along with the exception. If a try includes an except name as X: clause, the variable X will be assigned the instance provided in the raise:

try:

...

except IndexError as X: # X assigned the raised instance object

...

The as is optional in a try handler (if it’s omitted, the instance is simply not assigned to a name), but including it allows the handler to access both data in the instance and methods in the exception class.

This model works the same for user-defined exceptions we code with classes—the following, for example, passes to the exception class constructor arguments that become available in the handler through the assigned instance:

class MyExc(Exception): pass

...

raise MyExc('spam') # Exception class with constructor args

...

try:

...

except MyExc as X: # Instance attributes available in handler

print(X.args)

Because this encroaches on the next chapter’s topic, though, I’ll defer further details until then.

Regardless of how you name them, exceptions are always identified by instance objects, and at most one is active at any given time. Once caught by an except clause anywhere in the program, an exception dies (i.e., won’t propagate to another try), unless it’s reraised by another raise statement or error.

Propagating Exceptions with raise

A raise statement that does not include an exception name or extra data value simply reraises the current exception. This form is typically used if you need to catch and handle an exception but don’t want the exception to die in your code:

>>> try:

... raise IndexError('spam') # Exceptions remember arguments

... except IndexError:

... print('propagating')

... raise # Reraise most recent exception

...

propagating

Traceback (most recent call last):

File "", line 2, in

IndexError: spam

Running a raise this way reraises the exception and propagates it to a higher handler (or the default handler at the top, which

Return Main Page Previous Page Next Page

®Online Book Reader