zoukankan      html  css  js  c++  java
  • 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

  • 相关阅读:
    批量下载B站视频
    MATLAB安装
    printf小结
    hdoj 1874 dijkstra
    斐波那契而数列
    PAT数列排序
    感想
    物理定律的适用范围
    本博客的文章曾经恢复过,但迅速被部分删除(不知名的原因)
    (废墟重建)程序员如何学习书本上的例子 how programmers learn examples of books
  • 原文地址:https://www.cnblogs.com/xurui1995/p/5370112.html
Copyright © 2011-2022 走看看