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.

try:func1()except E:...def func1():try:func2()except E:...def func2():...raise E...Figure 29-1. Nested try/except statements: when an exception is raised (by you or by <strong>Python</strong>),control jumps back to the most recently entered try statement with a matching except clause, andthe program resumes after that try statement. Except clauses intercept and stop the exception—they are where you process and recover from exceptions.Once the exception is caught, its life is over—control does not jump back to allmatching trys that name the exception; only the first one is given the opportunity tohandle it. In Figure 29-1, for instance, the raise statement in the function func2 sendscontrol back to the handler in func1, and then the program continues within func1.By contrast, when try/finally statements are nested, each finally block is run inturn when an exception occurs—<strong>Python</strong> continues propagating the exception up toother trys, and eventually perhaps to the top-level default handler (the standarderror message printer). As Figure 29-2 illustrates, the finally clauses do not kill theexception—they just specify code to be run on the way out of each try during theexception propagation process. If there are many try/finally clauses active when anexception occurs, they will all be run, unless a try/except catches the exceptionsomewhere along the way.try:func1()finally:...def func1():try:func2()finally:...def func2():...raise E...Figure 29-2. Nested try/finally statements: when an exception is raised here, control returns to themost recently entered try to run its finally statement, but then the exception keeps propagating toall finallys in all active try statements, and eventually reaches the default top-level handler, wherean error message is printed. Finally clauses intercept (but do not stop) an exception—they are foractions to be performed “on the way out.”In other words, where the program goes when an exception is raised dependsentirely upon where it has been—it’s a function of the runtime flow of controlthrough the script, not just its syntax. The propagation of an exception essentiallyproceeds backward through time to try statements entered but not yet exited. Thispropagation stops as soon as control is unwound to a matching except clause, butnot as it passes through finally clauses on the way.618 | Chapter 29: Designing with Exceptions

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

Saved successfully!

Ooh no, something went wrong!