DekGenius.com
[ Team LiB ] Previous Section Next Section

24.1 Why Use Exceptions?

In a nutshell, exceptions let us jump out of arbitrarily large chunks of a program. Consider the pizza-making robot we talked about earlier in the book. Suppose we took the idea seriously and actually built such a machine. To make a pizza, our culinary automaton would need to execute a plan, which we implement as a Python program. It would take an order, prepare the dough, add toppings, bake the pie, and so on.

Now, suppose that something goes very wrong during the "bake the pie" step. Perhaps the oven is broken. Or perhaps our robot miscalculates its reach and spontaneously bursts into flames. Clearly, we want to be able to jump to code that handles such states quickly. Since we have no hope of finishing the pizza task in such unusual cases, we might as well abandon the entire plan.

That's exactly what exceptions let you do; you can jump to an exception handler in a single step, abandoning all suspended function calls. They're a sort of structured "super-goto."[1] An exception handler (try statement) leaves a marker and executes some code. Somewhere further ahead in the program, an exception is raised that makes Python jump back to the marker immediately, without resuming any active functions that were called since the marker was left. Code in the exception handler can respond to the raised exception as appropriate (calling the fire department, for instance). Moreover, because Python jumps to the handler statement immediately, there is usually no need to check status codes after every call to a function that could possibly fail.

[1] If you've used C, you may be interested to know that Python exceptions are roughly similar to C's setjmp/longjmp standard function pair. The try statement acts much like a setjmp, and raise works like a longjmp. But in Python, exceptions are based on objects and are a standard part of the execution model.

24.1.1 Exception Roles

In Python programs, exceptions are typically used for a variety of purposes. Here are some of their most common roles:


Error handling

Python raises exceptions whenever it detects errors in programs at runtime. You can either catch and respond to the errors in your code, or ignore the exception. If the error is ignored, Python's default exception-handling behavior kicks in—it stops the program and prints an error message. If you don't want this default behavior, code a try statement to catch and recover from the exception—Python jumps to your try handler when the error is detected, and your program resumes execution after the try.


Event notification

Exceptions can also signal a valid condition, without having to pass result flags around a program or test them explicitly. For instance, a search routine might raise an exception on failure, rather than returning an integer result code (and hoping that the code will never be a valid result).


Special-case handling

Sometimes a condition may happen so rarely that it's hard to justify convoluting your code to handle it. You can often eliminate special-case code by handling unusual cases in exception handlers instead.


Termination actions

As we'll see, the try/finally statement allows us to guarantee that required closing-time operations will be performed, regardless of the presence or absence of exceptions in our program.


Unusual control-flows

And finally, because exceptions are a sort of high-level "goto," you can use them as the basis for implementing exotic control flows. For instance, although backtracking is not part of the language itself, it can be implemented in Python with exceptions and a bit of support logic to unwind assignments.[2]

[2] True backtracking is an advanced topic that is not part of the Python language (even with addition of generator functions in 2.2), so we won't say more about it here. Roughly, backtracking undoes all computation before it jumps; Python exceptions do not (e.g., variables assigned between the time a try statement is entered and an exception is raised are not reset to their prior values). See a book on artificial intelligence or the Prolog or icon programming languages if you're curious.

We'll see such typical uses in action later in this part of the book. First, let's get started with a look at Python's exception-processing tools.

    [ Team LiB ] Previous Section Next Section