This question already has an answer here:
- When finally is executed? [duplicate] 10 answers
finally
always gets executed last, so the statement x = 3
should be executed last. But, when running this code, the value returned is 2.
Why?
class Test {
public static void main (String[] args) {
System.out.println(fina());
}
public static int fina()
{
int x = 0;
try {
x = 1;
int a = 10/0;
}
catch (Exception e)
{
x = 2;
return x;
}
finally
{
x = 3;
}
return x;
}
}
That's because the finally
block is executed after the catch
clause. Inside your catch
you return x
, and at that point its value is 2, which gets written to the stack as return value. Once finally
overwrites the value of x
with 3, the return value is already set to 2.
This is because you have a return statement in a catch block. Code is returning the value from that return statement even if the value is redefined in finally Block.
来源:https://stackoverflow.com/questions/57929659/why-return-is-not-honoring-the-value-of-variable-in-finally-block