12.07.2015 Views

Is Python a

Is Python a

Is Python a

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

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Example: Control-Flow NestingLet’s turn to an example to make this nesting concept more concrete. The followingmodule file, nestexc.py, defines two functions. action2 is coded to trigger an exception(you can’t add numbers and sequences), and action1 wraps a call to action2 in atry handler, to catch the exception:def action2( ):print 1 + [ ]# Generate TypeErrordef action1( ):try:action2( )except TypeError:print 'inner try'try:action1( )except TypeError:print 'outer try'# Most recent matching try# Here, only if action1 re-raises% python nestexc.pyinner tryNotice, though, that the top-level module code at the bottom of the file wraps a callto action1 in a try handler, too. When action2 triggers the TypeError exception,there will be two active try statements—the one in action1, and the one at the toplevel of the module file. <strong>Python</strong> picks and runs just the most recent try with a matchingexcept, which in this case is the try inside action1.As I’ve mentioned, the place where an exception winds up jumping to depends onthe control flow through the program at runtime. Because of this, to know whereyou will go, you need to know where you’ve been. In this case, where exceptions arehandled is more a function of control flow than of statement syntax. However, wecan also nest exception handlers syntactically—an equivalent case we’ll look at next.Example: Syntactic NestingAs I mentioned when we looked at the new unified try/except/finally statement inChapter 27, it is possible to nest try statements syntactically by their position in yoursource code:try:try:action2( )except TypeError:print 'inner try'except TypeError:print 'outer try'# Most recent matching try# Here, only if nested handler re-raisesNesting Exception Handlers | 619

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

Saved successfully!

Ooh no, something went wrong!