在try-catch-finally语句中,return和finally的关系

public class TestTryCatch {
public static void main(String[] args)
{
TestTryCatch test = new TestTryCatch();
int fun = test.fun();
System.out.println(fun);
}
public int fun()
{
int i = 10;
try
{
//doing something
return i;
}catch(Exception e){
return i;
}finally{
i = 20;
}
}
}

控制台输出:10

debug调试结果:先执行return i;然后执行finally语句,最后回到return i语句,但是finally语句不会改变返回值

结论:无论finally语句块中执行了什么操作,都无法影响返回值,所以试图在finally语句块中修改返回值是徒劳的。因此,finally语句块设计出来的目的只是为了让方法执行一些重要的收尾工作,而不是用来计算返回值的。

猜你喜欢

转载自blog.csdn.net/yituo7475/article/details/82982291