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;
    }
}

 

 

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