Skip to main content

Section 12.5 The finally clause of the try statement

A common programming pattern is to grab a resource of some kind — e.g. we establish a network connection to our internet service provider, or we may open a file for writing. Then we perform some computation which may raise an exception, or may work without any problems. Whatever happens, we want to “clean up” the resources we grabbed — e.g. disconnect from the network or close the file. The finally clause of the try statement is the way to do just this.
You put the keyword finally, a colon, and a block of code after your last except clause. The code in the finally clause is always executed, whether there was an error or not.
In this program, we need a nested set of try clauses: one for an error in the event that the file does not exist, another in the event that an error occurs while reading the file. We always want to close the file, whether there was a read error or not. Here is the file, with a line of bad data:
Data: bad_data.txt
23
47
86s
51
90