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呢?
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呢?
而i++;是先用后加。
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. 楼主,读一读
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. 楼主,读一读
try语句里如果出现return返回语句了,就先默认将该返回值给记住,然后先执行finally后的语句,最后再执行之前的返回语句return