【发布时间】:2012-08-12 05:45:00
【问题描述】:
试试这段代码。为什么 getValueB() 返回 1 而不是 2?毕竟, increment() 函数被调用了两次。
public class ReturningFromFinally
{
public static int getValueA() // This returns 2 as expected
{
try { return 1; }
finally { return 2; }
}
public static int getValueB() // I expect this to return 2, but it returns 1
{
try { return increment(); }
finally { increment(); }
}
static int counter = 0;
static int increment()
{
counter ++;
return counter;
}
public static void main(String[] args)
{
System.out.println(getValueA()); // prints 2 as expected
System.out.println(getValueB()); // why does it print 1?
}
}
【问题讨论】:
-
如果你有
finally { return increment(); },它将返回2。第一个return语句的表达式在finally 块之前计算。见Section §14.20.2 of the JLS。 -
或者如果他有 ++counter,它会在第二种方法中返回 2
getValue2 -
也许最好调用不同的 incrementxxx() 函数(一个在
return,另一个在finally),以不同的量递增,只是为了更好地了解问题 -
@ant 不,它不会。
counter++;和++counter;是表达式语句,效果相同。 -
是的,事实并非如此。在这种情况下,它们具有相同的效果,但并非总是如此 stackoverflow.com/a/24858/169277
标签: java return return-value finally