试试这段代码。为什么 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?
}
}