面试题:
try{}里有一个return语句,那么紧跟在这个try后的finally{}里的代码会不会被执行,什么时候被执行,在return前还是后?
正常反应finally里的代码一定会执行,但是是在retuen 前还是后呢? 不是很清楚的话就直接上代码验证下吧!
@Test
public void testReturn() {
System.out.println(test());
}
public int test() {
int a = 2;
try {
System.out.println("try代码块return前");
return a;
} finally {
System.out.println("finally 代码块");
}
}
输出:
try代码块return前
finally 代码块
2
由此可见finally里的代码会执行,且会在方法返回调用者前执行。
问题1:如果我们在finally 中修改了了返回值的值(此例指a变量的值),那么最终的返回值会变吗? 答案是不会,见如下例子
@Test
public void testReturn() {
System.out.println(test());
}
public int test() {
int a = 2;
try {
System.out.println("try代码块return前");
return a;
} finally {
a = 3;// 修改a变量的值
System.out.println("finally 代码块");
}
}
输出结果不变,依然是:
try代码块return前
finally 代码块
2
如果存在finally代码块,try中的return语句不会立马返回调用者,而是记录下返回值待finally代码块执行完毕之后再向调用者返回其值
问题2:如果我们在finally 中修改了了返回值的值(此例指a变量的值),并且使用return返回了修改后的值,那么最终的返回值会变吗? 答案是会,见如下例子
@Test
public void testReturn() {
System.out.println(test());
}
public int test() {
int a = 2;
try {
System.out.println("try代码块return前");
return a;
} finally {
a = 3;// 修改a变量的值
System.out.println("finally 代码块");
return 3;
}
}
输出结果变了,返回了3:
try代码块return前
finally 代码块
3
可见finally中的return最终会覆盖try中return的返回值,在finally中返回或者修改返回值会对程序造成很大的困扰,C#中直接用编译错误的方式来阻止程序员干这种龌龊的事情,Java中也可以通过提升编译器的语法检查级别来产生警告或错误,在IDEA会报一个警告.所以请不要在finally中使用return语句;
问题3:如果是try-catch-finaly结构的代码依然会怎样呢? 如果在3个代码块中发生异常会怎样呢?
public int test() {
int a = 1;
try {
System.out.println("发生运行时异常前");
int b = a/0;
System.out.println("发生运行时异常后");
return a;
}catch (Exception e){
a=2;
System.out.println("catch 代码块");
return a;
} finally {
a = 3;
return a;
}
}
我们利用除数为0模拟try中发生运行时异常,并添加catch捕获这个异常,并在catch中分别return了不同的的值,最终输出:
发生运行时异常前
catch 代码块
3
可见finally中的返回值也会覆盖catch中的返回值,我们再针对代码做个修改,在catch中也模拟发生异常,并去掉finally代码.
public int test() {
int a = 1;
try {
System.out.println("发生运行时异常前");
int b = a/0;
System.out.println("发生运行时异常后");
return a;
}catch (Exception e){
a=2;
System.out.println("catch 代码块发生异常前");
int b=a/0;
System.out.println("catch 代码块发生异常后");
return a;
}
最终输出:
发生运行时异常前
catch 代码块发生异常前java.lang.ArithmeticException: / by zero
可见最终程序会停止在发生异常的位置,无法正确的返回.此时如果把finally代码块补上会有什么效果呢?再来看一个例子:
public int test() {
int a = 1;
try {
System.out.println("发生运行时异常前");
int b = a/0;
System.out.println("发生运行时异常后");
return a;
}catch (Exception e){
a=2;
System.out.println("catch 代码块发生异常前");
int b=a/0;
System.out.println("catch 代码块发生异常后");
return a;
} finally {
a = 3;
return a;
}
}
输出:
发生运行时异常前
catch 代码块发生异常前
3
程序能够正常执行了,并返回finally中的值(此为3),这点我之前没想到,当我把catch代码块去掉的时候程序也能正产执行不抛异常,并返回finally中的值,但是把finally中的return语句去掉就会报错.所以这会给程序员造成一种困惑,实际发生异常的代码因为finally中return返回值的关系而把异常'屏蔽了'一样,非常不利于代码的理解与维护,所以还是那句话,一定不要在finally中使用return语句,否则会造成意想不到的执行效果.
最后说下finally的正确使用姿势:
finally里一般拿来做一些善后清理工作try块里出现错误的话,会立即跳出try块,找到匹配的错误,执行catch块里的语句
此时,可能在try块里打开的文件没关闭,连接的网络没断开,对这些浪费的内存就不能及时释放回收。如果有finally块的话,不管有没有出错,都会执行finally块里的内容。