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

原文地址:https://www.cnblogs.com/xurui1995/p/5370112.html