Online Book Reader

Home Category

Learning Python - Mark Lutz [474]

By Root 1437 0
"except-finally.py", line 9, in

func()

File "except-finally.py", line 3, in raise2

def raise2(): raise SyntaxError

SyntaxError: None

As we saw in Chapter 33, as of Python 2.5, except and finally clauses can be mixed in the same try statement. This makes some of the syntactic nesting described in this section unnecessary, though it still works, may appear in code written prior to Python 2.5 that you may encounter, and can be used as a technique for implementing alternative exception-handling behaviors.

Exception Idioms

We’ve seen the mechanics behind exceptions. Now let’s take a look at some of the other ways they are typically used.

Exceptions Aren’t Always Errors

In Python, all errors are exceptions, but not all exceptions are errors. For instance, we saw in Chapter 9 that file object read methods return an empty string at the end of a file. In contrast, the built-in input function (which we first met in Chapter 3 and deployed in an interactive loop in Chapter 10) reads a line of text from the standard input stream, sys.stdin, at each call and raises the built-in EOFError at end-of-file. (This function is known as raw_input in Python 2.6.)

Unlike file methods, this function does not return an empty string—an empty string from input means an empty line. Despite its name, the EOFError exception is just a signal in this context, not an error. Because of this behavior, unless the end-of-file should terminate a script, input often appears wrapped in a try handler and nested in a loop, as in the following code:

while True:

try:

line = input() # Read line from stdin

except EOFError:

break # Exit loop at end-of-file

else:

...process next line here...

Several other built-in exceptions are similarly signals, not errors—calling sys.exit() and pressing Ctrl-C on your keyboard, respectively, raise SystemExit and KeyboardInterrupt, for example. Python also has a set of built-in exceptions that represent warnings rather than errors; some of these are used to signal use of deprecated (phased out) language features. See the standard library manual’s description of built-in exceptions for more information, and consult the warnings module’s documentation for more on warnings.

Functions Can Signal Conditions with raise

User-defined exceptions can also signal nonerror conditions. For instance, a search routine can be coded to raise an exception when a match is found instead of returning a status flag for the caller to interpret. In the following, the try/except/else exception handler does the work of an if/else return-value tester:

class Found(Exception): pass

def searcher():

if ...success...:

raise Found()

else:

return

try:

searcher()

except Found: # Exception if item was found

...success...

else: # else returned: not found

...failure...

More generally, such a coding structure may also be useful for any function that cannot return a sentinel value to designate success or failure. For instance, if all objects are potentially valid return values, it’s impossible for any return value to signal unusual conditions. Exceptions provide a way to signal results without a return value:

class Failure(Exception): pass

def searcher():

if ...success...:

return ...founditem...

else:

raise Failure()

try:

item = searcher()

except Failure:

...report...

else:

...use item here...

Because Python is dynamically typed and polymorphic to the core, exceptions, rather than sentinel return values, are the generally preferred way to signal such conditions.

Closing Files and Server Connections

We encountered examples in this category in Chapter 33. As a summary, though, exception processing tools are also commonly used to ensure that system resources are finalized, regardless of whether an error occurs during processing or not.

For example, some servers require connections to be closed in order to terminate a session. Similarly, output files may require close calls to flush their buffers to disk, and input files may consume file descriptors if not closed; although

Return Main Page Previous Page Next Page

®Online Book Reader