zoukankan      html  css  js  c++  java
  • try-catch-finally的问题

    参考: https://blog.csdn.net/chengzhezhijian/article/details/17264531

    面试一家公司的面试题,注: 那个面试官对这个问题挺看重的(可是我回答对了,不知道原理)

    下面是测试
    public static int fun2(){ 
            try {
                System.out.println("哈哈哈");
                return 1;
            } catch (Exception e) {
                System.out.println("exception");
            }finally{
                System.out.println("finally");
            }
            return 100;
        }
    
        public static void main(String[] args) {
            System.out.println(fun6());
        }
    
        结果: 
                哈哈哈
                finally
                1          
       总结:  // 如果在try中返回数据,finally中的代码也会执行      
    

      

    //在try中返回数据,即使在finally中对此值做了修改,还是返回try中最后修改的数据
        public static int fun3(){ 
            int i = 1;
            try {
                System.out.println("哈哈哈");
                return i++;
            } catch (Exception e) {
                System.out.println("exception");
            }finally{
                ++i;
                System.out.println("finally");
            }
            return i;
        }
    结果:
        哈哈哈

        finally

          1

         总结: 虽然 finally中的代码执行了,并且修改了i的值,但是最后返回的还是之前的值

      

     //在finally代码块中返回数据,程序会提前退出,最后面return i 编译都通过不了
        public static int fun4(){ 
            int i = 1;
            try {
                System.out.println("哈哈哈");
            } catch (Exception e) {
                System.out.println("exception");
            }finally{
                ++i;
                System.out.println("finally");
                return i;
            }
    //        return i;
        }
        
       结果:
            哈哈哈
            finally
            2    
    

      try中的代码情况和catch中的一致,网上有说用引用类型不一样,这里我也测试了,引用类型在finally代码中修改和基本类型是一样的情况

      为什么会出现执行了finally中的代码,返回的值确没有变化呢,也查询了一些资料,目前的我的理解是这样 在finally代码中修改的值会存放在方法区, 而try中返回的i(基本数据类型) 是存在栈区的,所以最终返回的值不会因为finally做了改变而改变,同样引用类型的值是存放在堆区的,自然也不会改变

      上述仅个人总结,有不对的还望大佬指出!!

  • 相关阅读:
    angular 1.26 版本 window.history.back() 自动去顶部
    CK editor 制作 ”小“plugin
    CSS 3 过渡效果之jquery 的fadeIn ,fadeOut
    了解 : angular controller link nginit 顺序
    规范 : jobbox 中英文
    了解 : angular translate 和 google translate 和 微软 translate
    业务逻辑 : 未完 : easybook.com
    List和ArrayList的区别
    Select什么时候会产生重作日志
    几点对专用服务器与共享服务器差异的理解
  • 原文地址:https://www.cnblogs.com/liyong888/p/9035361.html
Copyright © 2011-2022 走看看