When try , finally combination is used, in try if there is a return statement.Why is finally block executed first?
class Palindrome
{
public static void main(String args[])
{
System.out.println(Palindrome.test());
}
public static int test()
{
try {
//return 0;
return 100;
}
finally {
System.out.println("finally trumps return.");
}
}
}
In the above code please tell me the flow of execution. I know that finally will be executed mandatorily after the try block.But in try block, return staatement will take the control to main class. In that case how will the control come to finally block?
Because that's the definition of a finally block. It always happens, regardless of how the block is exited. Finally blocks exist for operations that SHOULD always be performed, like closing open streams and cleaning up socket connections. No matter how the block is exited, the code within the finally block should always be performed. If you want to skip code if the try block is exited successfully, then it belongs in a catch() block with an appropriate exception type.
What do you mean by "first"?
The
finally
runs before execution leaves the method. When else should it run? It is, after all, part of the method.But if you have
then the method will still return 1. So the
return
statement does get executed before thefinally
block in a way (to determine the return value).If the question is why the finally block is executed at all, well, that's what they are for: To "finally" run after the "try" block is done, no matter what.
How? Well, that's just how the language (and runtime) work.
Before control flow is returned to the calling method, the finally block is executed.
It technically even has the option to change the return value (by having its own
return
statement), but that is highly discouraged.From https://docs.oracle.com/javase/tutorial/essential/exceptions/finally.html
Finally block is to design to always execute:
If you return in try block and code in finally block is not executed, this is not "always executes".
This makes code more readable if we do something necessary in finally block like unlock lock ,cleanup resources,which prevent some other new programmer(or yourself) add some code that returns or introduces exceptions in try block but without cleaning up the resources.
From https://docs.oracle.com/javase/tutorial/essential/exceptions/finally.html
There are some cases were the finally block may not execute. Follow the link to see what those are.
Thus the answer to your question is by design. Java is designed to work that way.