12.07.2015 Views

Is Python a

Is Python a

Is Python a

SHOW MORE
SHOW LESS
  • No tags were found...

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Chapter 29CHAPTER 29Designing with Exceptions29This chapter rounds out this part of the book with a collection of exception designtopics 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 ofdevelopment tools as well to help you as you make the migration from <strong>Python</strong> beginnerto <strong>Python</strong> application developer.Nesting Exception HandlersOur examples so far have used only a single try to catch exceptions, but what happensif one try is physically nested inside another? For that matter, what does itmean if a try calls a function that runs another try? Technically, try statements cannest in terms of syntax and the runtime control flow through your code.Both of these cases can be understood if you realize that <strong>Python</strong> stacks try statementsat runtime. When an exception is raised, <strong>Python</strong> returns to the most recentlyentered try statement with a matching except clause. Because each try statementleaves a marker, <strong>Python</strong> can jump back to earlier trys by inspecting the stackedmarkers. This nesting of active handlers is what we mean when we talk about propagatingexceptions up to “higher” handlers—such handlers are simply try statementsentered earlier in the program’s execution flow.Figure 29-1 illustrates what occurs when try/except statements nest at runtime. Theamount of code that goes into a try block can be substantial (e.g., it can containfunction calls), and it often invokes other code that may be watching for the sameexceptions. When an exception is eventually raised, <strong>Python</strong> jumps back to the mostrecently entered try statement that names that exception, runs that statement’sexcept clause, and then resumes after that try.617

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!