DekGenius.com
[ Team LiB ] Previous Section Next Section

24.4 The try/finally Statement

The other flavor of the try statement is a specialization and has to do with finalization actions. If a finally clause is used in a try, its block of statements are always run by Python "on the way out," whether an exception occurred while the try block was running or not. Its general form:

try:
    <statements>        # Run this action first.
finally:
    <statements>        # Always run this code on the way out.

Here's how this variant works. Python begins by running the statement block associated with the try header line first. The remaining behavior of this statement depends on whether an exception occurs during the try block or not:

  • If no exception occurs while the try block is running, Python jumps back to run the finally block, and then continues execution past the entire try statement.

  • If an exception does occur during the try block's run, Python comes back and runs the finally block, but then propagates the exception to a higher try or the top-level default handler; the program does not resume execution past the try statement.

The try/finally form is useful when you want to be completely sure that an action happens after some code runs, regardless of the exception behavior of the program. Note that the finally clause cannot be used in the same try statement as except and else, so it is best thought of as a distinct statement form.

24.4.1 Example: Coding Termination Actions with try/finally

We saw simple try/finally examples earlier. Here's a more realistic example that illustrates a typical role for this statement:

MyError = "my error"

def stuff(file):
    raise MyError

file = open('data', 'r')     # Open an existing file.
try:
    stuff(file)              # Raises exception
finally:
    file.close(  )                # Always close file.
...                          # Continue here if no exception.

In this code, we've wrapped a call to a file-processing function in a try with a finally clause, to make sure that the file is always closed, whether the function triggers an exception or not.

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 your closing-time (i.e., termination) activities always run. Python always runs the code in your finally blocks, regardless of whether an exception happens in the try block or not.[4] For example, if the function here did not raise an exception, the program would still execute the finally block to close your file, and then continue past the entire try statement.

[4] Unless Python crashes completely, of course. Python does a good job of avoiding crashes, by checking all possible errors as a program runs. When a program does crash hard, it is often due to a bug in linked-in C extension code, outside of Python's scope.

    [ Team LiB ] Previous Section Next Section