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.