

try: f = file('poem.txt')
while True: # our usual file-reading idiom
$ python finally.py
Programming is fun
When the work is done
Cleaning up...closed the file Traceback (most recent call last):
We do the usual file-reading stuff, but I've arbitrarily introduced a way of sleeping for 2 seconds before printing each line using thetime.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 aKeyboardInterrupt exception is thrown and the program exits, but before the program exits, the finally clause is executed and the file is closed.