A finally block contains code that should run after a try statement finishes, whether or not an exception occurs. It is mainly used for essential cleanup, such as closing files, database connections, or network resources.
How a finally block works
In exception handling, potentially unsafe code is placed in a try block. A catch block (called except in Python) can handle a matching exception, while the finally block executes after the attempted operation and any exception handling.
FileReader file = null;
try {
file = new FileReader("scores.txt");
// Read and process data
} catch (IOException error) {
System.out.println("The file could not be read.");
} finally {
if (file != null) {
file.close();
}
}
Here, the program attempts to open and process a file. If an IOException occurs, the catch block handles it. In either case, finally attempts to close the file so that the resource is not left open.
Outcome of the try block | What happens to finally? |
|---|---|
| The code completes normally | It executes afterward. |
| A matching exception is caught | It executes after the catch block. |
| An exception is not caught locally | It normally executes before the exception propagates. |
A return statement is reached | It normally executes before control leaves the method. |
| The program or runtime terminates abruptly | Execution is not guaranteed. |
The common misconception is that finally runs only when an exception occurs. This is incorrect: it normally runs regardless of whether the try block succeeds or fails. Its purpose is cleanup, not error detection or error handling.
IB exam technique
For B2.1 Programming fundamentals, explain both the control flow and the purpose. State that try contains code that may raise an exception, catch handles a specified exception, and finally performs cleanup afterward. In trace questions, follow the order precisely and avoid claiming that finally catches exceptions itself.