Sometimes you need to perform a clean-up action irrespective of whether an operation succeeds. In a later module we'll introduce context managers which are the modern solution to this common situation, but here we'll introduce the try … finally construct, since creating a context manager can be overkill in simple cases. In any case, an understanding of try … finally is useful for making your own context managers.
Consider this function, which uses various facilities of the standard library os module to change the current working directory, create a new directory at that location, and then restore the original working directory:
import os
def make_at(path, dir_name):
original_path = os.getcwd()
os.chdir(path)
os.mkdir(dir_name)
os.chdir(original_path)
At first sight this seems reasonable, but should the call to os.mkdir() fail...