• try {}里有一个return语句 finally执行顺序


    先看例子

    package example;
    
     
    class Demo{
        
    
    public static void main(String args[]) {  
    
        int x=1;
        System.out.println(Test(x));
      }
    
    private static int Test(int x) {
        try{
            return x;
        }
        finally{
            x++;
        }
        
     }
    }

     输出结果是1

    package example;
    
     
    class Demo{
        
    
    public static void main(String args[]) {  
    
        int x=1;
        System.out.println(Test(x));
      }
    
    private static int Test(int x) {
        try{
            return x;
        }
        finally{
            x++;
        return x; } } }

        输出2

    那么finally究竟是在try {}中的return之前还是之后执行的呢?

      try中的return语句调用的函数先于finally中调用的函数执行,也就是说return语句先执行,finally语句后执行Return并不是让函数马上返回,而是return语句执行后,将把返回结果放置进函数栈中,此时函数并不是马上返回,它要执行finally语句后才真正开始返回。

    以下代码可见运行过程

      

    public static void main(String args[]) {  
    
        int x=1;
        System.out.println(Test(x));
      }
    
    private static int Test(int x) {
        try{
            return fun1();
        }
        finally{
            
            return fun2();
        }
        
     }
    
    private static int fun1() {
        System.out.println("fun1()");
        return 1;
    }
    
    private static int fun2() {
        System.out.println("fun2()");
        return 2;
    }
    }

    fun1()
    fun2()
    2

  • 相关阅读:
    Flask11 Session、CSRF、注销session、利用端点自动跳转
    python学习笔记4-时间函数
    python学习笔记3-循环1
    python学习笔记2-条件语句
    python学习笔记1-基础语法
    sprintf系列函数
    sscanf非常的重要
    c++中.c_str和.c_data
    c++Map用法
    c语言sscanf总结
  • 原文地址:https://www.cnblogs.com/xurui1995/p/5370112.html
Copyright © 2020-2023  润新知