Skip to lesson

A finally block comes after try and catch. Its code runs every time: when the try block works, when a catch block runs, and even when the exception is not caught.

Code that always runs

An ATM must give your card back whether the withdrawal works or fails. A finally block, written after the catch blocks, holds such clean-up code: it runs after try every time, exception or not.

Example 1 · finally runs in both cases

ShareSweets.javaJava
public class ShareSweets {    public static void main(String[] args) {        int[] counts = {4, 0};        for (int people : counts) {            try {                System.out.println("Each gets " + 20 / people);            } catch (ArithmeticException e) {                System.out.println("No one to share with");            } finally {                System.out.println("-- done --");            }        }    }}
Output
Each gets 5
-- done --
No one to share with
-- done --

What this code does

  • With 4 people, the try block works, the catch is skipped, then finally runs.
  • With 0 people, the division throws, the catch block runs, then finally runs.
  • The order is always try, the catch blocks, then finally.

A try may also be followed by finally with no catch at all. It needs at least one of the two: a catch block or a finally block.

Even when nothing catches it

What if no catch block matches the exception? finally still runs, and only after it does the program stop with its stack trace.

Three paths: no exception (the rest of try runs), an exception that is caught (the catch block runs) and an exception that is not caught (no catch runs). All three go through finally. Then the code after it runs, or, when nothing caught the exception, the program stops.

Example 2 · finally runs even when the program stops

FinallyCrash.javaJava
public class FinallyCrash {    public static void main(String[] args) {        int[] marks = {78, 85};        try {            System.out.println(marks[2]);        } catch (ArithmeticException e) {            System.out.println("Maths problem");        } finally {            System.out.println("finally runs");        }        System.out.println("End");    }}
Sample output
finally runs
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 2 out of bounds for length 2
	at FinallyCrash.main(FinallyCrash.java:5)

What this code does

  • The catch block is for the wrong type, so the exception is not caught.
  • finally runs still prints before the stack trace. End never prints: the program stops after finally.

finally and return

A method may return from inside try. The finally block still runs before the method hands back its value, so its output appears first.

Trace the code

finally runs before the method returns

public class CheckMarks {
static String check(int marks) {
try {
if (marks >= 35) {
return "Pass";
}
return "Fail";
} finally {
System.out.println("Checked " + marks);
}
}
public static void main(String[] args) {
System.out.println(check(72));
System.out.println(check(20));
}
}

Variables

None yet.

Output

(nothing printed yet)

Line 14main calls check(72). println must wait for the answer.

Step 1 of 10

Closing a Scanner

A Scanner should be closed with sc.close() when you are done, but an exception before that line would skip it. Put sc.close() in finally, so it runs whatever the user types.

Example 3 · Closing a Scanner in finally

ReadAge.javaJava
import java.util.InputMismatchException;import java.util.Scanner;
public class ReadAge {    public static void main(String[] args) {        Scanner sc = new Scanner(System.in);        try {            System.out.print("Enter your age: ");            int age = sc.nextInt();            System.out.println("Next year you will be " + (age + 1));        } catch (InputMismatchException e) {            System.out.println("Please type a whole number");        } finally {            sc.close();            System.out.println("Scanner closed");        }    }}
Sample output
Enter your age: abc
Please type a whole number
Scanner closed

What this code does

  • InputMismatchException is in java.util, so it needs an import, just like Scanner.
  • The user typed abc, so the catch block ran. With 18, the try block would finish instead; either way finally closes the Scanner.
Close a Scanner on System.in only once, at the end of the program: after that it cannot read again, as in Reading after close() (opens in a new tab).

Next step

Check your understanding

8 quick questions