try、finally小结

  try/catch的用法我们都很熟悉,finally关键字也常与该代码块配合使用,用于申明无论是否捕获到异常都会执行的语句。我们分为以下几种情况测试以下finally语句对程序执行的影响:
  (1)返回值为基本数据类型:

    class A{
        //finally中对返回值做修改但不返回
        public int test1(){
            int i = 0;
            try {
                return i;
            }catch (Exception e){
                e.printStackTrace();
            }finally {
                i = 1;
            }
            return i;
        }
        //finally中对返回值做修改且返回
        public int test2(){
            int i = 0;
            try {
                return i;
            }catch (Exception e){
                e.printStackTrace();
            }finally {
                i = 1;
                return i;
            }
        }

    }
    public class Test {

        public static void main(String[] args){
            System.out.println(new A().test1());
            System.out.println(new A().test2());
        }

    }
    //测试结果:
    0
    1

  (2)返回值为引用类型:

    class B{
        String str = "abc";
    }
    class A{

        B b = new B();
      //finally修改返回值的成员但不返回
        public B test1(){
            try {
                return this.b;
            }catch (Exception e){
                e.printStackTrace();
            }finally {
                this.b.str = "def";
            }
            return this.b;
        }
       //finally修改返回值的成员且返回
        public B test2(){
            try {
                return this.b;
            }catch (Exception e){
                e.printStackTrace();
            }finally {
                this.b.str = "def";
                return this.b;
            }
        }

    }
    public class Test {

        public static void main(String[] args){
            System.out.println(new A().test1().str);
            System.out.println(new A().test2().str);
        }

    }
    //测试结果:
    def
    def

通过以上测试我们可以得出以下结论:

1、不管try,finally都一定会执行;
2、在try中return,在finally执行前会把结果保存起来,即使在finally中有修改也以try中保存的值为准,但如果是返回值
是引用类型,修改的属性会以finally修改后的为准;
3、如果try/finally都有return,直接返回finally中的return。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值