< BACKMake Note | BookmarkCONTINUE >
152015024128143245168232148039199167010047123209178152124239215162147038000013112057241206

try/finally

The try/finally statement is good for clean-up actions. The code in the finally block is always executed, no matter whether the try block fails or not.

					
1: try:
2:     f = open("c:\\autoexec.bat")
3:     lines = f.readlines()
4: finally:
5:     f.close()              # it is always executed
6: print "It is done"         # it is executed on success only

				

The previous piece of code opens a file and tries to read its lines. It is not necessary to check whether the process raises an error in order to close the file because the close function in line 5 is always executed, no matter what. Now, take a look at line 6. The print statement is only executed when the finally block is bypassed because when an error is raised, the finally block is executed and the program is terminated immediately afterwards if the exception is not handled, leaving the exception unhandled.

Tip

finally and except clauses cannot be used together along with a unique try clause.




Last updated on 1/30/2002
Python Developer's Handbook, © 2002 Sams Publishing

< BACKMake Note | BookmarkCONTINUE >

Index terms contained in this section

clauses
      except
      finally 2nd
      try
except clause
exceptions
      try/finally statement 2nd
finally clause 2nd
statements
      try/finally 2nd 3rd
try clause
try/finally statement 2nd 3rd

© 2002, O'Reilly & Associates, Inc.