当try、catch中有return时,finally中的代码会执行么?

本文探讨了在Java中try-catch-finally语句块内return语句的执行顺序。即使try或catch中有return,finally块也会被执行,且finally中的操作不会影响return的值。通过一个示例程序展示了这一特性,程序输出表明最终返回的值是在try或catch中确定的,不受finally中代码的影响。

在try catch finally 中不管try catch 中有没有return 都会执行finally 并且return的值会先执行但是将值保存起来,等finally执行结束返回结果,不管finally是否改变值,返回结果不变。

public static void main(String[] args) {

int b = test();

System.out.println(b);

}

 

public static int test() {

int x = 1;

try {

return x++;

}catch(Exception e) {

e.printStackTrace();

} finally {

System.out.println("finally:" + x);

++x;

System.out.println("++x:" + x);

}

return x;

}

运行结果:

finally:2
++x:3
1

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值