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.

• If an exception does occur during the try block’s run, <strong>Python</strong> still comes backand runs the finally block, but then propagates the exception up to a higher tryor the top-level default handler; the program does not resume execution belowthe try statement. That is, the finally block is run even if an exception is raised,but unlike an except, the finally does not terminate the exception—it continuesbeing raised after the finally block runs.The try/finally form is useful when you want to be completely sure that an actionwill happen after some code runs, regardless of the exception behavior of the program.In practice, it allows you to specify cleanup actions that always must occur,such as file closes, and server disconnections.Note that the finally clause cannot be used in the same try statement as except andelse in <strong>Python</strong> 2.4 and earlier, so the try/finally is best thought of as a distinctstatement form if you are using an older release. In <strong>Python</strong> 2.5, however, finally canappear in the same statement as except and else, so today, there is really a single trystatement with many optional clauses (more about this shortly). Whichever versionyou use, though, the finally clause still serves the same purpose—to specify“cleanup” actions that must always be run, regardless of any exceptions.As we’ll see later in this chapter, in <strong>Python</strong> 2.6, the with statement andits context managers provide an object-based way to do similar workfor exit actions; however, this statement also supports entry actions.Example: Coding Termination Actions with try/finallyWe saw some simple try/finally examples earlier. Here’s a more realistic examplethat illustrates a typical role for this statement:class MyError(Exception): passdef stuff(file):raise MyError( )file = open('data', 'w') # Open an output filetry:stuff(file)# Raises exceptionfinally:file.close( )# Always close file to flush output buffers... # Continue here only if no exceptionIn this code, we’ve wrapped a call to a file-processing function in a try with afinally clause to make sure that the file is always closed, and thus finalized, whetherthe function triggers an exception or not. This way, later code can be sure that thefile’s output buffer’s content has been flush from memory to disk. A similar codestructure can guarantee that server connections are closed, and so on.588 | Chapter 27: Exception Basics

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

Saved successfully!

Ooh no, something went wrong!