How to Handle Exceptions in Python Using the finally Clause

By John Paul Mueller

Normally you want to handle any exception that occurs in a way that doesn’t cause your Python application to crash. However, sometimes you can’t do anything to fix the problem, and the application is most definitely going to crash.

At this point, your goal is to cause the application to crash gracefully, which means closing files so that the user doesn’t lose data and performing other tasks of that nature. Anything you can do to keep damage to data and the system to a minimum is an essential part of handling data for a crashing application.

The finally clause is part of the crashing-application strategy. You use this clause to perform any required last-minute tasks. Normally, the finally clause is quite short and uses only calls that are likely to succeed without further problem.

It’s essential to close the files, log the user off, and perform other required tasks, and then let the application crash before something terrible happens (such as a total system failure). With this necessity in mind, the following steps show a simple example of using the finally clause.

1Open a Python File window.

You see an editor in which you can type the example code.

2Type the following code into the window — pressing Enter after each line:

import sys
 raise ValueError
 print("Raising an exception.")
except ValueError:
 print("ValueError Exception!")
 print("Taking care of last minute details.")
print("This code will never execute.")

In this example, the code raises a ValueError exception. The except clause executes as normal when this happens. The call to sys.exit() means that the application exits after the exception is handled. Perhaps the application can’t recover in this particular instance, but the application normally ends, which is why the final print() function call won’t ever execute.

The finally clause code always executes. It doesn’t matter whether the exception happens or not. The code you place in this block needs to be common code that you always want to execute. For example, when working with a file, you place the code to close the file into this block to ensure that the data isn’t damaged by remaining in memory rather than going to disk.

3Choose Run→Run Module.

You see a Python Shell window open. The application displays the except clause message and the finally clause message. The sys.exit() call prevents any other code from executing.

4Comment out the raise ValueError call by preceding it with two pound signs, like this:

##raise ValueError

Removing the exception will demonstrate how the finally clause actually works.

5Save the file to disk.

This ensures that Python sees the change.

6Choose Run→Run Module.

You see a Python Shell window open. The application displays a series of messages, including the finally clause message. This part of the example shows that the finally clause always executes, so you need to use it carefully.