[ Team LiB ] |
24.4 The try/finally StatementThe 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:
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/finallyWe 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.
|
[ Team LiB ] |