Card 06/ 10

GotchaDifficulty: Intermediate1 min

Why finally Runs Even After return

A method returns 1, and the caller receives 2. There is one return 1; in the source and nothing reassigns the variable.

java
static int value() {
    try {
        return 1;
    } finally {
        System.out.println("finally ran");
    }
}
text
finally ran
1

A finally block runs on every way out of the try — falling off the end, returning, breaking, or throwing. The return on line 3 works out its value, then finally runs, then the method actually returns.

That much is useful and is what finally is for. The expensive version is a return inside the finally itself.

java
static int value() {
    try {
        return 1;
    } finally {
        return 2;
    }
}

Never return or throw from a finally block. Use it for cleanup and nothing else, and let whatever the try decided be what leaves the method.