Reputation: 5247
Code:
public String get() {
try {
//doSomething
return "Hello";
}
finally {
System.out.print("Finally");
}
How does this code execute?
Upvotes: 3
Views: 4038
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
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
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