直接来看一下题目,就是在try catch finally中放入return ,来看返回的顺序,这个在日常的代码编写中应该是很常用的了吧?不算是面试造航母~ 大概考察了几种情况: 一下 i 初始值都是 0
1、catch中有return,finally中的代码会执行吗?
public static int test1(int i){
try {
throw new Exception("异常");
} catch (Exception e) {
System.out.println("catch~~~~~~~");
return i;
} finally {
System.out.println("finally~~~~~~~");
}
}
catch~~~~~~~
finally~~~~~~~
0
2、catch中有return,finally也有return,怎么执行?
结果显示finally中的return会比catch中return先执行
public static int test1(int i){
try {
throw new Exception("异常");
} catch (Exception e) {
System.out.println("catch~~~~~~~");
return 0;
} finally {
System.out.println("finally~~~~~~~");
return 1;
}
}
catch~~~~~~~
finally~~~~~~~
1
前边两个一般问题都不大,下面是重点
3、catch中return变量,finally对变量做计算,返回结果是啥?
按照往常的逻辑,输入0 ,经过++i,返回1没毛病呀!
public static int test1(int i){
try {
throw new Exception("异常");
} catch (Exception e) {
System.out.println("catch~~~~~~~");
return i;
} finally {
int i1 = ++i;
System.out.println("finally~~~~~~~"+i1);
}
}
catch~~~~~~~
finally~~~~~~~1
0
fuck! 咋是0? i 赋初值为0,捕获到异常后进入 catch,catch 里有return,但是后边还有 finally,先执行 finally里的,对i+1=1,然后 return。那 return 的是1?事实上不是1,而是0.为何?
可以清楚的看到i=1;但是返回的确是0?那说明此i非彼i,就是返回的i不是这个i。 因为这里是值传递,在执行return前,保留了一个i的副本,值为0,然后再去执行finally,finall完后,到return的时候,返回的并不是当前的i,而是保留的那个副本,也就是0.所以返回结果是0.
4、 catch、finally同时return变量,返回结果又该是啥?
如果finally中有return不会走catch
public static void main(String[] args) {
System.out.println(test1(0));
}
public static int test1(int i){
try {
throw new Exception("异常");
} catch (Exception e) {
System.out.println("catch~~~~~~~");
return i;
} finally {
int i1 = ++i;
System.out.println("finally~~~~~~~"+i1);
return i;
}
}
catch~~~~~~~
finally~~~~~~~1
1
总结: 在catch中有return的情况下,finally中的内容还是会执行,并且是先执行finally再return。
需要注意的是,如果返回的是一个基本数据类型,则finally中的内容对返回的值没有影响。、因为返回的是finally执行之前生成的一个副本。
当catch和finally都有return时,return的是finally的值。