• try{ return }finally{}中的return


    try 中的 return 语句调用的函数先于 finally 中调用的函数执行,也就是说 return 语句先执行,finally 语句后执行,但 return 并不是让函数马上返回结果,而是 return 语句执行后,将把返回结果放置进函数栈中,此时函数并不是马上返回结果,它要执行 finally 语句后才真正开始返回,,但此时finally块中的代码已经影响不了return返回的值了

    public class Demo {
        public static void main(String[] args) {
            System.out.println(num());
        }
    
        public static int num(){
            int i = 0;
            try {
                i = 1;
                return i;
            }catch (Exception e){
    
            }finally {
                i = 2;
            }
            return i;
        }
    }
    
    打印结果:1
    

    返回的是基本数据类型,直接返回值

    public class Demo {
        public static void main(String[] args) {
            System.out.println(num().getI());
        }
    
        public static Test num() {
            Test t = new Test();
            try {
                t.setI(1);
                return t;
            } catch (Exception e) {
    
            } finally {
                t.setI(2);
            }
            return t;
        }
    }
    
    class Test{
        private int i ;
    
        public int getI() {
            return i;
        }
    
        public void setI(int i) {
            this.i = i;
        }
    }
    
    打印结果:2
    

    返回的是对象的引用

  • 相关阅读:
    模板方法模式
    策略模式
    享元模式
    组合模式
    桥接模式
    外观模式
    代理模式
    装饰者模式
    适配器模式
    类之间的关联关系和依赖关系
  • 原文地址:https://www.cnblogs.com/tian-ci/p/10543072.html
Copyright © 2020-2023  润新知