Chapter 35. 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 fundamentals portion of 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? Technically, 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 35-1
illustrates what occurs when try
statements with except clauses nest
at runtime. The amount of code that goes into a try block can be substantial, and it may contain function ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access