public class TestReturn {
public static void main(String[] args) {
System.out.println(test());
}
static int test() {
int i = 1;
try{
return i;
} finally {
++i;
System.out.println("finally...");
}
}
}
大家可能会家到过这样一道面试题:
try {}里有一个return语句,那么紧跟在这个try后的finally {}里的code会不会被执行,什么时候被执行,在return前还是后?
当然可能也看到了答案:会在return之前执行。
问题:既然是在return之前执行,那么输出的结果为什么是1而不是2呢?

解决方案 »

  1.   

    因为你的finally{}操作是 ++i; 先加再用的。。
    而i++;是先用后加。
      

  2.   

    a finally clause is always entered with a reason. That reason may be that the try code finished normally, that it executed a control flow statement such as return, or that an exception was thrown in code executed in the TRy block. The reason is remembered when the finally clause exits by falling out the bottom. However, if the finally block creates its own reason to leave by executing a control flow statement (such as break or return) or by throwing an exception, that reason supersedes the original one, and the original reason is forgotten. For example, consider the following code: 
    try { 
        // ... do something ... 
        return 1; 
    } finally { 
        return 2; 

    When the TRy block executes its return, the finally block is entered with the "reason" of returning the value 1. However, inside the finally block the value 2 is returned, so the initial intention is forgotten. In fact, if any of the other code in the try block had thrown an exception, the result would still be to return 2. If the finally block did not return a value but simply fell out the bottom, 
    the "return the value 1" reason would be remembered and carried out. 楼主,读一读
      

  3.   

    a finally clause is always entered with a reason. That reason may be that the try code finished normally, that it executed a control flow statement such as return, or that an exception was thrown in code executed in the TRy block. The reason is remembered when the finally clause exits by falling out the bottom. However, if the finally block creates its own reason to leave by executing a control flow statement (such as break or return) or by throwing an exception, that reason supersedes the original one, and the original reason is forgotten. For example, consider the following code: 
    try { 
        // ... do something ... 
        return 1; 
    } finally { 
        return 2; 

    When the TRy block executes its return, the finally block is entered with the "reason" of returning the value 1. However, inside the finally block the value 2 is returned, so the initial intention is forgotten. In fact, if any of the other code in the try block had thrown an exception, the result would still be to return 2. If the finally block did not return a value but simply fell out the bottom, 
    the "return the value 1" reason would be remembered and carried out. 楼主,读一读
      

  4.   

    楼上几位说的都不标准到位:下面请听下我的讲解如有不足,请多多指教
    try语句里如果出现return返回语句了,就先默认将该返回值给记住,然后先执行finally后的语句,最后再执行之前的返回语句return