The finally block
16 min · Beginner
Need help? Ask a tutor on WhatsApp (opens in a new tab)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
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 --"); } } }}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
finallyruns. - With 0 people, the division throws, the catch block runs, then
finallyruns. - 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.
Example 2 · finally runs even when the program stops
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"); }}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 runsstill prints before the stack trace.Endnever 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
Variables
None yet.
Output
(nothing printed yet)Line 14main calls check(72). println must wait for the answer.
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
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"); } }}Enter your age: abc Please type a whole number Scanner closed
What this code does
InputMismatchExceptionis injava.util, so it needs animport, just likeScanner.- The user typed
abc, so the catch block ran. With18, the try block would finish instead; either wayfinallycloses the Scanner.
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