Finally语句块中的代码什么时候被执行?

1. 如果在try{} 语句块中有return语句,finally语句块中没有return语句,finally语句块中的代码在return语句前执行。
当 try{} 和 finally{} 中都存在return语句块,finally语句块中的return语句会覆盖其他return语句。

public class TestFinally
{
    public static int testFinally1()
    {
        try{
            return 1;
        }catch(Exception e){
            return 0;
        }finally{
            System.out.println("execute finally1");
            return 3;
        }
    }
    public static void main(String[] args) 
    {
        int result = testFinally1();
        System.out.println(result);     
    }
}
//结果
execute finally1
3

2. 在 finally{} 语句块中修改return语句中的返回值

1)修改的返回值为基本数据类型,改. 变return的值对返回值没有任何影响。程序执行到return时首先将返回值存储到一个指定的位置,再去执行finally语句块。在方法中,定义的基本数据类型的变量都存储在栈中,当这个函数结束以后,其对应的栈就会被回收,因此返回时不时直接返回变量的值,而是返回复制的值。

public class TestFinally
{
public static int testFinally2()
    {
        int result = 1;
        try{
            result = 2;
            return result;//执行到此处,返回值被复制
        }catch(Exception e){
            return 0;
        }finally{
            result = 3;//改变result的值与复制result的值谁先谁后?
            System.out.println("execute finally2");
    }
    public static void main(String[] args) 
    {
        int resultVal = testFinally2();
        System.out.println(resultVal);      
    }
}
    
//结果:
execute finally2
2  

2)修改的返回值为引用类型,定义该类型的数据变量时,数据是存放在堆中的,在调用return语句之前,首先把变量的副本存储的一个指定位置,并不是将它的值复制到指定位置。此时复制的引用还是只想原来的值。因此在finally语句块中修改引用类型的值,是会改变return中的值的。

public class TestFinally
{
    public static StringBuffer testFinally3()
    {
        StringBuffer s = new StringBuffer("hello");
        try{
            return s;
        }catch(Exception e){
            return null;
        }finally{
            s.append(" world");
            System.out.println("execute finally3");
        }
    }
    public static void main(String[] args) 
    {
        StringBuffer resultString = testFinally3();
        System.out.println(resultString);   
    }
}
//结果:
execute finally3
hello world

在try/catch中有return时,在finally块中改变基本类型的数据对返回值没有任何影响;而在finally中改变引用类型的数据会对返回结果有影响。

finally语句块一定会被执行吗?

当程序进入try语句之前就出现异常时,会直接结束,不会执行finally语句块中的语句代码。即没有进入语句块时。
当程序在try语句块中强制退出时也不会执行finally语句块中的代码。

System.exit(0);
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值