Skip to lesson

The finally block and its traps

A program opens a file, then an error or an early return jumps out halfway. The file must still be closed every single time. Java gives you one place for that, and it has a few traps.

When finally runs

A finally block is the part of a try statement that runs after the try and any catch, whether or not an exception happened, so that clean-up work is never skipped.

finally is the block at the end of a try statement that always runs once the try (and a matching catch, if any) is done.

Four ways out of a try statement: ends normally, exception caught, exception not caught, and return inside try. In every one, the finally block runs; then the program carries on, the error goes up, or the method returns.

Example 1 · finally in four situations

WhenFinallyRunsDemo.javaJava
public class WhenFinallyRunsDemo {    static void run(int caseNo) {        try {            System.out.println("case " + caseNo + ": try starts");            if (caseNo == 2) {                Integer.parseInt("abc");            }            if (caseNo == 3) {                Object fee = null;                fee.toString();            }            if (caseNo == 4) {                System.out.println("case 4: returning early");                return;            }            System.out.println("case " + caseNo + ": try ends");        } catch (NumberFormatException e) {            System.out.println("case " + caseNo + ": caught " + e.getClass().getSimpleName());        } finally {            System.out.println("case " + caseNo + ": finally");        }        System.out.println("case " + caseNo + ": after the try statement");    }
    public static void main(String[] args) {        for (int i = 1; i <= 4; i++) {            try {                run(i);            } catch (RuntimeException e) {                System.out.println("main caught " + e.getClass().getSimpleName());            }            System.out.println();        }    }}
Output
case 1: try starts
case 1: try ends
case 1: finally
case 1: after the try statement

case 2: try starts
case 2: caught NumberFormatException
case 2: finally
case 2: after the try statement

case 3: try starts
case 3: finally
main caught NullPointerException

case 4: try starts
case 4: returning early
case 4: finally

What this code does

  • Case 1 ends normally, case 2 is caught, case 3 is not caught by run, and case 4 returns early. finally prints in all four.
  • In case 3 the NullPointerException waits while finally runs, then leaves run, so "after the try statement" is skipped and main catches it. In case 4 the return also skips that line, but only after finally.

It runs in all four normal cases: the try ends normally, an exception is caught, an exception is not caught, or the try leaves early with return, break or continue. When the exception is not caught, finally runs first and then the exception continues up to the caller. The same goes for return: finally runs before the method actually returns.

That is why finally holds clean-up work that must never be skipped: closing a file, releasing a lock, printing "connection closed". A try may even have no catch at all: try { ... } finally { ... } is valid.

System.exit: the exception to the rule

System.exit(status) stops the whole JVM at once. No more code runs in that program, so a finally around the call is skipped.

Example 2 · System.exit skips finally

ExitSkipsFinallyDemo.javaJava
public class ExitSkipsFinallyDemo {    public static void main(String[] args) {        int registered = 0;        try {            System.out.println("Checking registrations...");            if (registered == 0) {                System.out.println("No students registered. Exiting.");                System.exit(0);            }            System.out.println("Printing hall tickets");        } finally {            System.out.println("finally: closing the exam database");        }    }}
Output
Checking registrations...
No students registered. Exiting.

What this code does

  • System.exit(0) ends the JVM immediately with status 0, so the finally line is never printed.
  • If the database really had to be closed, the program should close it before calling System.exit, or simply return from main and let finally run.

The same is true when the JVM itself dies: the process is killed from outside, the power goes off, or the JVM crashes. finally is a promise made by running Java code, so it cannot help when Java stops running. So finally is reliable for clean-up inside a running program, but not for "must happen even if the computer fails" work, such as saving money transfers. Those need a database transaction or a similar tool outside the program.

Order of try, catch and finally output

The order is fixed. The try block runs until it ends or throws. If it threw, the first matching catch runs. Then finally runs. Last comes either the code after the whole statement, or the pending return or uncaught exception.

Example 3 · The return value is saved before finally

FinallyOrderDemo.javaJava
public class FinallyOrderDemo {    static int attempts = 0;
    static int bookSeat(String coach) {        int seat = 0;        try {            System.out.println("try: booking in " + coach);            attempts++;            seat = Integer.parseInt(coach.substring(1)) * 10;            return seat;        } catch (NumberFormatException e) {            System.out.println("catch: bad coach " + coach);            seat = -1;            return seat;        } finally {            seat = 999;   // too late: the return value is already saved            System.out.println("finally: attempts = " + attempts);        }    }
    public static void main(String[] args) {        System.out.println("result " + bookSeat("S4"));        System.out.println("result " + bookSeat("SX"));    }}
Output
try: booking in S4
finally: attempts = 1
result 40
try: booking in SX
catch: bad coach SX
finally: attempts = 2
result -1

What this code does

  • The order is try, (catch), finally, and only then the caller prints result. The finally line always appears before the result.
  • return seat; saves 40 (or -1) first. Setting seat = 999 in finally changes the variable, not the saved value, so 999 never comes out.

A return inside try or catch works in two steps. First the return value is worked out and saved. Then finally runs, and only after that does the method really return. So changing a local int in finally does not change what the method returns. If the saved value is an object, such as a StringBuilder or a list, changes made to that object inside finally are visible, because the saved value points to the same object.

Order of execution

Which line runs when?

The try throws an exception. Tap the steps in the order Java runs them.

try {
System.out.println("A");
int x = 1 / 0;
System.out.println("B");
} catch (ArithmeticException e) {
System.out.println("C");
} finally {
System.out.println("D");
}
System.out.println("E");

A return inside finally hides the real result

A return in finally replaces whatever the try or catch was about to do. It throws away the saved return value, and it also throws away an exception that was on its way to the caller, with no trace at all.

Example 4 · Trap: return in finally

ReturnInFinallyDemo.javaJava
public class ReturnInFinallyDemo {    static int marksFromServer(String roll) {        try {            if (roll.isEmpty()) {                throw new IllegalArgumentException("roll number is empty");            }            return 87;        } finally {            return -1;   // hides both the real result and the exception        }    }
    public static void main(String[] args) {        System.out.println("CS101: " + marksFromServer("CS101"));        System.out.println("empty: " + marksFromServer(""));    }}
Output
CS101: -1
empty: -1

What this code does

  • For CS101 the try saves 87, but the return -1 in finally replaces it. Every call returns -1.
  • For an empty roll the IllegalArgumentException is thrown away completely: main never sees it. The fix is to delete the return from finally.

The compiler accepts it. Only with javac -Xlint:finally does it print the warning "finally clause cannot complete normally". Treat that warning as an error: never return (or break or continue out) from a finally block.

Predict the output

What comes back?

Read the code and pick what it prints.

Round 1 of 3

What does this program print?

public class SeatDemo {
static int book() {
try {
return 1;
} finally {
System.out.println("clean");
}
}
public static void main(String[] args) {
System.out.println(book());
}
}

An exception thrown in finally replaces the original one

If code in finally throws, its new exception replaces the original one. The caller sees only the clean-up problem, such as "printer offline", and the real cause, such as "payment over limit", is lost.

Example 5 · Trap: an exception thrown in finally

FinallyThrowsDemo.javaJava
public class FinallyThrowsDemo {    static void printReceipt(boolean printerOnline) {        if (!printerOnline) {            throw new IllegalStateException("receipt printer offline");        }        System.out.println("receipt printed");    }
    static void payBad(int amount) {        try {            if (amount > 5000) {                throw new IllegalArgumentException("amount over limit: " + amount);            }            System.out.println("paid " + amount);        } finally {            printReceipt(false);   // throws and replaces the real problem        }    }
    static void payGood(int amount) {        try {            if (amount > 5000) {                throw new IllegalArgumentException("amount over limit: " + amount);            }            System.out.println("paid " + amount);        } finally {            try {                printReceipt(false);            } catch (IllegalStateException e) {                System.out.println("warning: " + e.getMessage());            }        }    }
    public static void main(String[] args) {        try {            payBad(8000);        } catch (RuntimeException e) {            System.out.println("payBad -> caller sees: " + e.getMessage());        }        try {            payGood(8000);        } catch (RuntimeException e) {            System.out.println("payGood -> caller sees: " + e.getMessage());        }    }}
Output
payBad -> caller sees: receipt printer offline
warning: receipt printer offline
payGood -> caller sees: amount over limit: 8000

What this code does

  • In payBad the "over limit" exception is on its way out when finally throws "printer offline". The new exception wins and the real cause disappears.
  • payGood wraps the clean-up in its own try-catch. The printer problem becomes a warning, and the caller still gets the real reason the payment failed.

The fix is to protect risky clean-up with its own small try-catch inside finally, and report the clean-up problem without throwing it. The next module shows try-with-resources, which keeps both exceptions automatically.

Next step

Check your understanding

12 quick questions