As per the answer here, it is stated that if we have return statement inside the try/catch block then before executing the return statement finally block will be executed.
But I am seeing some unexpected output for the below code:
Output
In try block, value is : 20
In finally block, value is : 40
In main method, value is : 20
Before returning value from the try block, the value of 'x' is set to 40 in finally. But this is returning x's value as 20 instead of 40, to main method.
Can someone please explain, how is it working internally?
class ExceptionTest
{
private static int returnValue() {
int x = 10;
try {
x=20;
System.out.println("In try block, value is : " + x);
return x;
}
finally {
x = 40;
System.out.println("In finally block, value is : " + x);
}
}
public static void main (String[] args) throws java.lang.Exception
{
System.out.println("In main method, value is : " + returnValue());
}
}