How do try, catch and finally interact in Java, and in what exact order do they run?
The three blocks run in a fixed order, and knowing that order answers most of the questions that people ask about them.
The try block runs first. If it finishes without throwing anything, the catch block is skipped completely and the finally block runs next. If the try block does throw something, the matching catch block runs, and then the finally block runs after it.
The finally block runs on every path through the statement. It runs whether the code succeeded, whether it threw an error, and whether it returned early.
public class Main {
public static void main(String[] args) {
System.out.println("result : " + compute(true));
System.out.println("result : " + compute(false));
}
static String compute(boolean shouldFail) {
try {
if (shouldFail) {
throw new IllegalStateException("something went wrong");
}
return "all good";
} catch (IllegalStateException e) {
return "caught the problem";
} finally {
System.out.println("finally always runs");
}
}
}
So the answer to the question is this. The try block runs first, the catch block runs only if something was thrown, and the finally block runs last and always.
There is one detail that catches people out, and it is about the return value. When the try block returns a value, that value is worked out first, but the finally block still runs before the method actually gives the value back. So the finally block has the last word about what the caller receives.
The next question in this topic looks at that in more detail.