Sub topic 6
Running Code No Matter What: finally
Sometimes you need a step to run every time, whether your code worked or failed. You might want to print a "done" message, or give back something you borrowed, like an open file. Java has a tool for this called the finally block.
What finally Does
A finally block is a block of code that comes after try and any catch blocks. Java runs it in every one of these cases:
- The
tryblock finishes normally. - An exception is thrown and a
catchblock handles it. - An exception is thrown and no
catchblock matches it. - The
tryorcatchblock hits areturnstatement.
The basic shape looks like this:
public class Shape {
public static void main(String[] args) {
try {
System.out.println("Trying something");
} catch (RuntimeException e) {
System.out.println("Handling the problem");
} finally {
System.out.println("Cleaning up");
}
}
}A Worked Example
In this program, divide returns from inside try. It can also return from inside catch. The finally block still runs in both cases.
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));
}
}Running it prints:
finally always runs
5
Failed: java.lang.ArithmeticException: / by zero
finally always runs
0Here is what happens, step by step:
divide(10, 2)computes5and gets ready to return it.- Before the method actually returns, Java runs
finally. That is why "finally always runs" prints before5. divide(10, 0)throws anArithmeticException, because you cannot divide by zero.- The
catchblock prints the error and gets ready to return0. finallyruns again, and only then does0come back tomain.
try and finally Without catch
You can also write try with finally and leave out catch. Your cleanup still runs, but the exception keeps moving up to the caller.
public class NoCatch {
public static void main(String[] args) {
try {
System.out.println("Working");
throw new IllegalStateException("broken");
} finally {
System.out.println("Cleanup still happens");
}
}
}The program prints both lines. Then it stops with the IllegalStateException, because nothing caught it.
Why This Matters
The most common use of finally is cleanup: closing files, network connections, and other resources. The next chapter explains why that cleanup is harder to get right than it looks.
Exercise
A method has try { return "A"; } finally { System.out.println("B"); }. You call it with System.out.println(method());. What prints, and in what order?
Show answer
"B" prints first, then "A". The finally block runs before the method finishes returning, and only after that does the caller print the returned value "A".
Exercise
If the try block throws an exception and no catch block matches it, does the finally block run?
Show answer
Yes. The finally block runs first, and then the exception continues up to the calling method.