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.

This particular example’s function isn’t all that useful (it just raises an exception),but wrapping calls in try/finally statements is a good way to ensure that yourclosing-time (i.e., termination) activities always run. Again, <strong>Python</strong> always runs thecode in your finally blocks, regardless of whether an exception happens in the tryblock. *When the function here raises its exception, the control flow jumps back, and runsthe finally block to close the file. The exception is then propagated on to eitheranother try or the default top-level handler, which prints the standard error messageand shuts down the program; the statement after this try is never reached. If thefunction here did not raise an exception, the program would still execute the finallyblock to close your file, but it would then continue below the entire try statement.Also, notice that the user-defined exception here is again defined with a class—aswe’ll see in the next chapter, exceptions today should all be class instances.Unified try/except/finallyIn all versions of <strong>Python</strong> prior to Release 2.5 (for its first 15 years of life, more orless), the try statement came in two flavors, and was really two separate statements—wecould either use a finally to ensure that cleanup code was always run, orwrite except blocks to catch and recover from specific exceptions and optionallyspecify an else clause to be run if no exceptions occurred.That is, the finally clause could not be mixed with except and else. This was partlybecause of implementation issues, and partly because the meaning of mixing the twoseemed obscure—catching and recovering from exceptions, seemed a disjoint conceptfrom performing cleanup actions.In <strong>Python</strong> 2.5, though (the version of <strong>Python</strong> used in this edition of this book), thetwo statements have merged. Today, we can mix finally, except, and else clauses inthe same statement. That is, we can now write a statement of this form:try:main-actionexcept Exception1:handler1except Exception2:handler2...else:else-blockfinally:finally-block* Unless <strong>Python</strong> crashes completely, of course. It does a good job of avoiding this, though, by checking allpossible errors as a program runs. When a program does crash hard, it is often due to a bug in linked-in Cextension code, outside of <strong>Python</strong>’s scope.Unified try/except/finally | 589

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

Saved successfully!

Ooh no, something went wrong!