A Byte of Python

Try..Finally

What if you were reading a file and you wanted to close the file whether or not an exception was raised? This can be done using the finally block. Note that you can use an except clause along with a finally block for the same corresponding try block. You will have to embed one within another if you want to use both.

Using Finally

Example 13.3. Using Finally

				
#!/usr/bin/python
# Filename: finally.py

import time

try:
	f = file('poem.txt')
	while True: # our usual file-reading idiom
		line = f.readline()
		if len(line) == 0:
			break
		time.sleep(2)
		print line,
finally:
	f.close()
	print 'Cleaning up...closed the file'
				
				

Output

				
$ python finally.py
Programming is fun
When the work is done
Cleaning up...closed the file
Traceback (most recent call last):
  File "finally.py", line 12, in ?
    time.sleep(2)
KeyboardInterrupt
				
				

How It Works

We do the usual file-reading stuff, but I've arbitrarily introduced a way of sleeping for 2 seconds before printing each line using the time.sleep method. The only reason is so that the program runs slowly (Python is very fast by nature). When the program is still running, press Ctrl-c to interrupt/cancel the program.

Observe that a KeyboardInterrupt exception is thrown and the program exits, but before the program exits, the finally clause is executed and the file is closed.