Chapter 29. Designing with Exceptions
This chapter rounds out this part of the book with a collection of exception design topics and common use case examples, followed by this part’s gotchas and exercises. Because this chapter also closes out the book at large, it includes a brief overview of development tools as well to help you as you make the migration from Python beginner to Python application developer.
Nesting Exception Handlers
Our examples so far have used only a single
try to catch exceptions, but what happens if one
try is physically nested inside another? For that matter, what does it mean if a
try calls a function that runs another
try statements can nest in terms of syntax and the runtime control flow through your code.
Both of these cases can be understood if you realize that Python stacks
try statements at runtime. When an exception is raised, Python returns to the most recently entered
try statement with a matching
except clause. Because each
try statement leaves a marker, Python can jump back to earlier
trys by inspecting the stacked markers. This nesting of active handlers is what we mean when we talk about propagating exceptions up to “higher” handlers—such handlers are simply
try statements entered earlier in the program’s execution flow.
Figure 29-1 illustrates what occurs when
except statements nest at runtime. The amount of code that goes into a
try block can be substantial (e.g., it can contain function calls), and it often invokes other ...