Online Book Reader

Home Category

Learning Python - Mark Lutz [451]

By Root 1398 0
so try/finally is a more general termination structure. On the other hand, with/as may also run startup actions and supports user-defined context management code.

* * *

Why You Will Care: Error Checks


One way to see how exceptions are useful is to compare coding styles in Python and languages without exceptions. For instance, if you want to write robust programs in the C language, you generally have to test return values or status codes after every operation that could possibly go astray, and propagate the results of the tests as your programs run:

doStuff()

{ # C program

if (doFirstThing() == ERROR) # Detect errors everywhere

return ERROR; # even if not handled here

if (doNextThing() == ERROR)

return ERROR;

...

return doLastThing();

}

main()

{

if (doStuff() == ERROR)

badEnding();

else

goodEnding();

}

In fact, realistic C programs often have as much code devoted to error detection as to doing actual work. But in Python, you don’t have to be so methodical (and neurotic!). You can instead wrap arbitrarily vast pieces of a program in exception handlers and simply write the parts that do the actual work, assuming all is well:

def doStuff(): # Python code

doFirstThing() # We don't care about exceptions here,

doNextThing() # so we don't need to detect them

...

doLastThing()

if __name__ == '__main__':

try:

doStuff() # This is where we care about results,

except: # so it's the only place we must check

badEnding()

else:

goodEnding()

Because control jumps immediately to a handler when an exception occurs, there’s no need to instrument all your code to guard for errors. Moreover, because Python detects errors automatically, your code usually doesn’t need to check for errors in the first place. The upshot is that exceptions let you largely ignore the unusual cases and avoid error-checking code.

* * *

Chapter Summary

And that is the majority of the exception story; exceptions really are a simple tool.

To summarize, Python exceptions are a high-level control flow device. They may be raised by Python, or by your own programs. In both cases, they may be ignored (to trigger the default error message), or caught by try statements (to be processed by your code). The try statement comes in two logical formats that, as of Python 2.5, can be combined—one that handles exceptions, and one that executes finalization code regardless of whether exceptions occur or not. Python’s raise and assert statements trigger exceptions on demand (both built-ins and new exceptions we define with classes); the with/as statement is an alternative way to ensure that termination actions are carried out for objects that support it.

In the rest of this part of the book, we’ll fill in some of the details about the statements involved, examine the other sorts of clauses that can appear under a try, and discuss class-based exception objects. The next chapter begins our tour by taking a closer look at the statements we introduced here. Before you turn the page, though, here are a few quiz questions to review.

Test Your Knowledge: Quiz

Name three things that exception processing is good for.

What happens to an exception if you don’t do anything special to handle it?

How can your script recover from an exception?

Name two ways to trigger exceptions in your script.

Name two ways to specify actions to be run at termination time, whether an exception occurs or not.

Test Your Knowledge: Answers

Exception processing is useful for error handling, termination actions, and event notification. It can also simplify the handling of special cases and can be used to implement alternative control flows. In general, exception processing also cuts down on the amount of error-checking code your program may require—because all errors filter up to handlers, you may not need to test the outcome of every operation.

Any uncaught exception eventually filters up to the default exception handler Python provides at the top of your program. This handler prints the familiar error message and shuts down your program.

Return Main Page Previous Page Next Page

®Online Book Reader