What if you wanted some statements to execute after the try block whether or not an exception was raised? This is done using the finally block. Note that if you are using a finally block, you cannot have any except clauses for the same try block.
Example 13.3. Using Finally
#!/usr/bin/python # Filename: finally.py try: f = file('poem.txt') while True: # Our usual file-reading block l = f.readline() if len(l) == 0: break print l, finally: print 'Cleaning up...' f.close()
$ python finally.py Programming is fun When the work is done if (you wanna make your work also fun): use Python! Cleaning up...