Search code examples
javatry-catchfinally

Why code in finally will execute even it has returned in try block?


Code:

public String get() {
try {
     //doSomething
     return "Hello";
}
finally {
     System.out.print("Finally");
}

How does this code execute?


Solution

  • Because that's the whole point of a finally block - it executes however you leave the try block, unless the VM itself is shut down abruptly.

    Typically finally blocks are used to clean up resources - you wouldn't want to leave a file handle open just because you returned during the try block, would you? Now you could put that clean-up code just before the return statement - but then it wouldn't be cleaned up if the code threw an exception instead. With finally, the clean-up code executes however you leave the block, which is generally what you want.

    See JLS section 14.20.2 for more details - and note how all paths involve the finally block executing.