Hesey
Hesey

Reputation: 5247

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?

Upvotes: 3

Views: 4038

Answers (3)

Michael Borgwardt
Michael Borgwardt

Reputation: 346310

That's exactly what finally is for: the code inside will execute when the try block is left, no matter how (except the JVM shutting down via System.exit() or external reasons).

Upvotes: 0

James Bedford
James Bedford

Reputation: 28962

Finally ALWAYS gets executed, no matter what happens in the try block (fail, return, exception, finish etc.).

If you don't want this code to be executed, you could always placed it after the try/catch/finally statement.

Upvotes: 3

Jon Skeet
Jon Skeet

Reputation: 1500565

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.

Upvotes: 17

Related Questions