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.

... print 'after fetch'...'m'after fetchHere, if the try block finishes without an exception, the finally block will run, andthe program will resume after the entire try. In this case, this statement seems a bitsilly—we might as well have simply typed the print right after a call to the function,and skipped the try altogether:fetcher(x, 3)print 'after fetch'There is a problem with coding this way, though: if the function call raises an exception,the print will never be reached. The try/finally combination avoids thispitfall—when an exception does occur in a try block, finally blocks are executedwhile the program is being unwound:>>> def after( ):... try:... fetcher(x, 4)... finally:... print 'after fetch'... print 'after try?'...>>> after( )after fetchTraceback (most recent call last):File "", line 1, in ?File "", line 3, in afterFile "", line 2, in fetcherIndexError: string index out of rangeHere, we don’t get the “after try?” message because control does not resume after thetry/finally block when an exception occurs. Instead, <strong>Python</strong> jumps back to run thefinally action, but then propagates the exception up to a prior handler (in this case,to the default handler at the top). If we change the call inside this function so as notto trigger an exception, the finally code still runs, but the program continues afterthe try:>>> def after( ):... try:... fetcher(x, 3)... finally:... print 'after fetch'... print 'after try?'...>>> after( )after fetchafter try?>>>580 | Chapter 27: Exception Basics

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

Saved successfully!

Ooh no, something went wrong!