Sub topic 6
Running Code No Matter What: finally
Some code has to run whether things go well or badly. Say you turn on a "busy" light when a task starts. The light should go off when the task ends, even if the task crashed. Java gives you a place for that kind of code. It is called the finally block.
A finally block is a block of code attached to a try statement. Java runs it after the try block, and after any catch block, every time. It runs if the code succeeds. It runs if an exception is caught. It even runs if an exception is not caught at all.
The Shape of try, catch, and finally
You already know try and catch. A finally block goes at the end:
public class Shape {
public static void main(String[] args) {
try {
System.out.println("1. try block runs");
} catch (RuntimeException e) {
System.out.println("2. catch block runs only if something failed");
} finally {
System.out.println("3. finally block always runs");
}
}
}Output:
1. try block runs
3. finally block always runsNothing failed, so the catch block was skipped. The finally block ran anyway.
You can have at most one finally block. It must come after all the catch blocks.
A Worked Example
This example comes from the tutorial plan. It uses a multi-catch clause, which you met in the last chapter, and adds a finally block.
public class FinallyDemo {
static int divide(int a, int b) {
try {
return a / b;
} catch (ArithmeticException | IllegalArgumentException e) {
System.out.println("Failed: " + e);
return 0;
} finally {
System.out.println("finally always runs");
}
}
public static void main(String[] args) {
System.out.println(divide(10, 2));
System.out.println(divide(10, 0));
}
}Output:
finally always runs
5
Failed: java.lang.ArithmeticException: / by zero
finally always runs
0Let's go through it step by step.
divide(10, 2)computes10 / 2, which is5. Thereturnstatement gets ready to send back5.- Before the method really ends, Java runs the
finallyblock. It prints "finally always runs". - Now the method returns
5, andmainprints it. divide(10, 0)tries10 / 0. Integer division by zero throws anArithmeticException.- The
catchblock prints the error and gets ready to return0. - Again, the
finallyblock runs first. Then0is returned and printed.
Notice the order in the output. The finally message appears before the number. That is because finally runs before the method hands its value back to the caller.
finally Without catch
You do not need a catch block to use finally. A try followed only by finally is allowed. This is useful when you cannot fix the problem here, but you still need to clean up.
public class NoCatch {
public static void main(String[] args) {
try {
System.out.println("start");
int[] numbers = new int[2];
numbers[5] = 1;
System.out.println("this line never runs");
} finally {
System.out.println("finally runs before the crash report");
}
}
}Output:
start
finally runs before the crash report
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 5 out of bounds for length 2
at NoCatch.main(NoCatch.java:6)The array has only two slots, so numbers[5] throws an exception. No catch block handles it. Java still runs finally first. After that, the exception keeps moving up and ends the program.
When Does finally Run?
This table sums up the common cases.
| What happens in the try block | Does catch run? | Does finally run? | What happens after finally |
|---|---|---|---|
| Finishes normally | No | Yes | Code after the try statement runs |
| Hits a `return` | No | Yes | The method returns |
| Throws an exception that a catch matches | Yes | Yes | Code after the try statement runs, unless catch returned or threw |
| Throws an exception no catch matches | No | Yes | The exception goes up to the caller |
| `break` or `continue` inside a loop | No | Yes | The loop breaks or continues |
| Calls `System.exit()` | No | No | The program stops right away |
The last row is the main exception to "always". System.exit() shuts down the Java program on the spot, so there is no chance to run finally. If the computer loses power or the process is killed, finally does not run either.
Edge Case: Changing a Returned Value
What if finally changes a variable that the try block is returning?
public class ReturnValue {
static int count() {
int x = 1;
try {
return x;
} finally {
x = 99;
System.out.println("finally set x to " + x);
}
}
public static void main(String[] args) {
System.out.println("count() returned " + count());
}
}Output:
finally set x to 99
count() returned 1The method returns 1, not 99. When Java reaches return x;, it saves a copy of the value 1. Changing x later does not change that saved copy.
Edge Case: return Inside finally
You can write return inside a finally block. You almost never should.
public class LostException {
static int risky() {
try {
throw new RuntimeException("something important broke");
} finally {
return -1;
}
}
public static void main(String[] args) {
System.out.println("risky() returned " + risky());
}
}Output:
risky() returned -1The exception is gone. The return in finally replaced it, and nobody ever learns that something broke. The same thing happens if finally throws its own exception: the new exception replaces the old one.
What finally Is Good For
Use finally for cleanup, meaning work that undoes or releases something the try block started. Common examples:
- Turning off a "busy" flag or status light.
- Printing a "done" log message.
- Releasing a lock so other parts of the program can continue.
- Closing a file or network connection.
Here is the busy-flag idea as real code:
public class BusyFlag {
static boolean busy = false;
static void doWork(boolean fail) {
busy = true;
try {
System.out.println("working... busy = " + busy);
if (fail) {
throw new IllegalStateException("work failed");
}
} finally {
busy = false;
}
}
public static void main(String[] args) {
doWork(false);
System.out.println("after success, busy = " + busy);
try {
doWork(true);
} catch (IllegalStateException e) {
System.out.println("caught: " + e.getMessage());
}
System.out.println("after failure, busy = " + busy);
}
}Output:
working... busy = true
after success, busy = false
working... busy = true
caught: work failed
after failure, busy = falseThe flag is reset both times. Without finally, a failure would leave busy stuck at true.
Closing files is the most common use of finally, and it turns out to be hard to get right. A later chapter, "Why Closing Resources Is Hard," explains why. After that, you will learn try-with-resources, which handles closing for you.
Exercises
Exercise
What does this method print, and what does it return? static String test() { try { System.out.println("A"); return "B"; } finally { System.out.println("C"); } }
Show answer
It prints "A", then "C", and then returns "B". The return value "B" is saved when return runs, the finally block prints "C", and then the method finishes returning "B".
Exercise
A try block calls System.exit(0). The try statement has a finally block that prints "bye". Does "bye" get printed? Why or why not?
Show answer
No. System.exit(0) stops the Java program immediately, so the finally block never gets a chance to run. This is the main case where finally does not run.
Exercise
Why is it a bad idea to write return inside a finally block?
Show answer
A return in finally replaces whatever the try or catch block was doing. If an exception was being thrown, it is thrown away silently, so the real error is lost and very hard to find.
Exercise
Write a method greet(String name) that prints "Hello, " followed by name.toUpperCase(), and always prints "greet finished" afterward, even when name is null. Do not catch the exception.
Show answer
static void greet(String name) { try { System.out.println("Hello, " + name.toUpperCase()); } finally { System.out.println("greet finished"); } } When name is null, name.toUpperCase() throws a NullPointerException. The finally block prints "greet finished", and then the exception goes up to the caller.