Part 06 / Topic 4 of 8
finally: the part that always runs
A finally block runs after the try/catch, whether the try succeeded, an exception was caught, or even if the try block hit a return. It is the right place for "this must happen no matter what" work — in this course's scope, that mostly means logging or counting; Part 7 adds closing files, where finally matters even more.
static int readAmount(String text) {
try {
int amount = Integer.parseInt(text);
return amount; // finally still runs before this return actually happens
} catch (NumberFormatException e) {
return -1;
} finally {
System.out.println(" finally: counter attempt logged");
}
}
Real output (examples/03_finally_always_runs.java), three cases: success, a caught exception, and an exception that is only caught outside the block with the finally:
$ javac 03_finally_always_runs.java
$ java FinallyAlwaysRuns
Case 1: valid amount
try: parsing "1500"
try: returning 1500
finally: counter attempt logged
Result: 1500
Case 2: invalid amount
try: parsing "abc"
catch: not a number, returning -1
finally: counter attempt logged
Result: -1
Case 3: finally runs even when the exception is NOT caught
try: about to divide by zero
finally: cleanup ran even though nothing caught the error here
Outer catch finally got it: / by zero
Notice Case 1: finally printed before main saw the returned value 1500. Java finishes the finally block first, then completes the return. In Case 3, there is no catch around the inner try, yet finally still ran before the exception kept travelling outward to the catch in main.
Full program: examples/03_finally_always_runs.java.
Done here? The practice set for Part 6 — including the solutions — is on the part page.