11.3 Finally Block

A finally clause always executes when its try block executes regardless of whether an exception occurs.

But finally is useful for more than just exception handling — it allows the programmer to avoid having cleanup code accidentally bypassed by a return, continue, or break. Putting cleanup code in a finally block is always a good practice, even when no exceptions are anticipated.

In following program the try block of the main method opens a FileReader. The program should close that stream before exiting. This poses a somewhat complicated problem because try block can exit in one of three ways.

  1. The new FileReader statement fails and throws an IOException.
  2. The inFile.nextInt() statement fails and throws an InputMismatchException.
  3. Everything succeeds and the try block exits normally.

The runtime system always executes the statements within the finally block regardless of what happens within the try block. So it's the perfect place to perform cleanup.

import java.io.FileReader;
import java.io.IOException;
import java.util.InputMismatchException;
import java.util.Scanner;

public class ReadNum 
    public static void main(String[] args) 
            Scanner inFile = new Scanner(new FileReader("sample.txt");
            int num1 = inFile.nextInt();
            int num2 = inFile.nextInt();

            int sum = num1 + num2;

            System.out.println("Sum: " + sum);
        catch (IOException | InputMismatchException ex) 
            System.out.println("Error: " + ex.toString());

Sample Run # 1 (without creating sample.txt)

Error: java.io.FileNotFoundException: sample.txt 
(The system cannot find the file specified)

Sample Run # 2 (when sample.txt containts text)

Error: java.util.InputMismatchException

Sample Run # 3 (when sample.txt contains integers)

Sum: 17

The finally block is a key tool for preventing resource leaks. When closing a file or otherwise recovering resources, place the code in a finally block to ensure that resource is always recovered.

Try-with-resources in Java 7 is a new exception handling mechanism that makes it easier to correctly close resources that are used within a try-catch block expained in next section.