See All Titles |
![]() ![]() try/finallyThe 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.
|
Index terms contained in this sectionclausesexcept 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. |