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.

Again, the finally block is always run on the way out, regardless of what happenedin the main action, and regardless of any exception handlers run in the nested try(trace through the four cases listed previously to see how this works the same). However,this equivalent is more obscure, and requires more code than the new mergedform. Mixing from into the same statement is easier to write and read, and so is thepreferred technique today.Unified try ExampleHere’s a demonstration of the merged try statement form at work. The followingcodes four common scenarios, with print statements that describe the meaning ofeach:print '-' * 30, '\nEXCEPTION RAISED AND CAUGHT'try:x = 'spam'[99]except IndexError:print 'except run'finally:print 'finally run'print 'after run'print '-' * 30, '\nNO EXCEPTION RAISED'try:x = 'spam'[3]except IndexError:print 'except run'finally:print 'finally run'print 'after run'print '-' * 30, '\nNO EXCEPTION RAISED, ELSE RUN'try:x = 'spam'[3]except IndexError:print 'except run'else:print 'else run'finally:print 'finally run'print 'after run'print '-' * 30, '\nEXCEPTION RAISED BUT NOT CAUGHT'try:x = 1 / 0except IndexError:print 'except run'finally:print 'finally run'print 'after run'Unified try/except/finally | 591

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

Saved successfully!

Ooh no, something went wrong!