java面试题,try-catch-finally的返回结果

 代码:

package com.example.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class DemoApplication {

    public static void main(String[] args) {
        System.out.println(MyException.testTryCatchFinally());
        System.out.println(MyException.testTryFinally());
        SpringApplication.run(DemoApplication.class, args);
    }

}

class MyException {

    /*
    该方法输出结果是3
    * */
    public static int testTryCatchFinally() {
        int num = 0;
        try {
            num++;
            int i = 1 / 0;
            return num;
        } catch (Exception ex) {
            num++;
            System.out.println(ex.getMessage());
        } finally {
            num++;
            //return num; 这里不能有return
        }
        return num;
    }

    /*
   该方法输出结果是1不是2!!!!!
   * */
    public static int testTryFinally() {
        int num = 0;
        try {
            num++;
            return num;
        } catch (Exception ex) {
            num++;
            System.out.println(ex.getMessage());
        } finally {
            num++;
            //return num; 这里不能有return
        }
        return num;
    }
}

执行结果:

结果分析:看看try-catch-finally结构反编译的代码,一目了然。

try{ }结构中使用了局部变量var2,并在执行finally{}结构前把num的值赋给var2,作为返回值

//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//

package com.example.demo;

class MyException {
    MyException() {
    }

    public static int testTryCatchFinally() {
        int num = 0;

        try {
            ++num;
            int i = 1 / 0;
            int var2 = num;
            return var2;
        } catch (Exception var6) {
            ++num;
            System.out.println(var6.getMessage());
        } finally {
            ++num;
        }

        return num;
    }

    public static int testTryFinally() {
        int num = 0;

        try {
            ++num;
            int var1 = num;
            return var1;
        } catch (Exception var5) {
            ++num;
            System.out.println(var5.getMessage());
        } finally {
            ++num;
        }

        return num;
    }
}

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章