In Java, the try keyword marks the risky region, the catch keyword handles what goes wrong, and the finally keyword runs the cleanup afterwards whatever happened. They cooperate in a fixed order, and the interesting part is the edges. What runs when the method returns early, what runs when the exception is never caught, and what happens when the catch blocks are written in the wrong order.
The previous lesson in this module covered "What Is the Exception Hierarchy and What Throws What?", and the next lesson in this module is about "What Is the Difference Between Checked and Unchecked Exceptions?".
What does each of the three keywords do?
The try keyword holds the code that might fail. If it completes normally, then the catch blocks are skipped entirely. If it throws something, then the runtime walks down the catch clauses looking for the first one whose type matches, hands the control to it, and skips the rest. The finally keyword runs after that, no matter which path was taken.
public class CatchFinallyDemo {
public static void main(String[] args) {
System.out.println("before try");
try {
System.out.println("inside try");
int value = Integer.parseInt("not a number");
System.out.println(value);
} catch (NumberFormatException e) {
System.out.println("caught: " + e.getMessage());
} finally {
System.out.println("finally always runs");
}
System.out.println("after try");
}
}The output is this.
before try
inside try
caught: For input string: "not a number"
finally always runs
after tryTwo details in that output are worth pausing on. The statement after the throwing call never runs, so a try block that fails half way through leaves the rest of it skipped. Put only the risky statement in the try, and not a long sequence of unrelated work. And the catch block ran before the finally block, which is always the order.
A third point follows from the same structure. The try block has its own scope, and a variable that is declared inside it is not visible in the catch or the finally blocks. That is usually what you want, but it means that a value which you intend to check after a failure has to be declared before the try. You declare it there, you leave it empty, and you assign it inside the try, and then the catch block has something concrete to inspect.
Which catch block wins when more than one could match?
The first one that matches, evaluated from the top down. That is why the order of the catch clauses is not cosmetic. Java refuses to compile a list where a broader type comes first, because the narrower clause underneath could never run.
import java.io.IOException;
public class CatchOrderDemo {
static void run(String mode) throws IOException {
if (mode.equals("io")) {
throw new IOException("file missing");
}
throw new IllegalArgumentException("bad argument");
}
public static void main(String[] args) {
String[] modes = { "io", "arg" };
for (String mode : modes) {
try {
run(mode);
} catch (IllegalArgumentException e) {
System.out.println(mode + " -> IllegalArgumentException: " + e.getMessage());
} catch (IOException e) {
System.out.println(mode + " -> IOException: " + e.getMessage());
} catch (Exception e) {
System.out.println(mode + " -> some other Exception");
}
}
}
}The output is this.
io -> IOException: file missing
arg -> IllegalArgumentException: bad argumentSwap the first two clauses and the compiler stops you. The message names the problem exactly.
error: exception IOException has already been caughtNotice that the catch clause for Exception at the bottom never fires in that run, because both of the failures are covered by the two narrower clauses above it. A trailing catch-all is still worth having, but it should be the last resort and it should do something specific rather than just print a message.
Does finally still run when the method returns?
It does. A return inside the try block does not skip the finally block. The runtime finishes the finally block first, and then it returns. That makes finally a plausible place for the cleanup, and also a trap, because a return inside finally quietly discards the value that the method was about to hand back.
public class FinallyReturnDemo {
static int compute() {
try {
return 1;
} finally {
System.out.println("finally runs even on return");
return 2;
}
}
public static void main(String[] args) {
System.out.println("result: " + compute());
}
}The output is this.
finally runs even on return
result: 2The method was supposed to return 1 and it returns 2 instead. The compiler does not warn you about this, so you should treat a return inside a finally block as a bug in waiting. The same applies to a throw inside finally. It replaces whatever was in flight.
Does finally run when the exception is not caught?
It does, and that is what makes finally useful for the cleanup. The finally block belongs to the try statement and not to the catch blocks, so it runs while the exception is still on its way up the stack.
public class FinallyWithExceptionDemo {
static void risky() {
try {
System.out.println("working");
throw new IllegalStateException("cannot continue");
} finally {
System.out.println("cleanup done before the exception leaves");
}
}
public static void main(String[] args) {
try {
risky();
} catch (IllegalStateException e) {
System.out.println("caller saw: " + e.getMessage());
}
}
}The output is this.
working
cleanup done before the exception leaves
caller saw: cannot continueThe order is worth stating explicitly. The finally block runs first, then the exception continues on its way and it is caught further up the stack. If no catch block anywhere up the chain matches, then the program prints the stack trace and it exits.
When does finally do more harm than good?
There are three situations to watch for. First, a call to System.exit() inside a try block skips the finally block entirely, because the runtime is tearing down rather than unwinding. Second, an exception thrown inside finally replaces the original failure and hides it, so you should never start the cleanup work that can throw unless you catch it there. Third, closing a resource in finally works, but it is easy to forget the close on the exception path. The manual pattern in the next lesson's example shows exactly that bug.
For anything that owns a resource, prefer the resource-closing construct that is described in the try-with-resources lesson instead of a hand-written finally block. There is one more subtlety that is worth knowing. If the finally block completes abruptly, then the runtime discards whatever the try block was doing, including a pending exception. You will rarely trigger that by accident, but it is why the libraries that use finally internally are careful about what they put in it.
The alternative to finally is often better than finally. You catch the failure, you add the context that your caller needs, and you rethrow it as a different type while keeping the original as the cause. That reads better than a cleanup block, because the handling sits next to the failure that it handles, and it removes the temptation to put a return inside a finally block. When the cleanup is a resource close rather than a status update, then use the resource-closing construct instead of hand-rolling either pattern.
Three rules to keep
- Try blocks should hold the smallest possible risky region, so an unexpected failure does not skip unrelated work.
- Catch clauses run top to bottom and the first match wins, and the compiler rejects a broader clause that is placed before a narrower one.
- Finally always runs, including on a return and on an escaping exception, so you should never put a return or a throw inside it.
Try it yourself: build a small program with a method that takes an integer and divides ten by it inside a try block, catching ArithmeticException and printing a friendly message. Add a finally block that prints "cleanup done". Then call the method with zero and with two, and write down the exact order of the three output lines in each case. Finally, add a return inside the finally block and confirm by running it that the return value of the method changes, and then remove it again.