try…finally…&return

public static void main(String[] args) {
        int result = m();
        System.out.println(result); 
    }
​
    private static int m() {
        int i = 100;
        try {
            return i;
        } finally {
            i++;
        }
    }
}

IntelliJ IDEA反编译的结果:

//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by FernFlower decompiler)
//
​
package com.example.exception;
​
public class ExceptionTest15 {
    public ExceptionTest15() {
    }
​
    public static void main(String[] args) {
        int result = m();
        System.out.println(result);
    }
​
    private static int m() {
        byte i = 100;
​
        byte var1;
        try {
            var1 = i;
        } finally {
            int var5 = i + 1;
        }
​
        return var1;
    }
}

jad反编译的结果:

// jadx decompiler
public class ExceptionTest15 {
    public static void main(String[] args) {
        int result = m();
        System.out.println(result);
    }
​
    private static int m() {
        try {
            int i = 100 + 1;
            return 100;
        } catch (Throwable th) {
            int i2 = 100 + 1;
            throw th;
        }
    }
}
​
public static void main(String[] args) {
        int result = m();
        System.out.println(result); // 100
    }
​
    /*
     * 结果是 100
     * Java语法规则(有一些规则是不能破坏的)
     *   Java中有这样一条规则:
     *       Java方法体中的代码必须是自上而下顺序依次逐行执行。
     *   Java中还有这样一条规则:
     *       return语句一旦执行,整个方法就执行结束。
     * */
    private static int m() {
        int i = 100;
        try {
            //  这行代码出现在int = 100;的下面,所以最终结果一定是100。
            // return必须保证最后执行。一旦执行,整个方法结束。
            return i;
        } finally {
            i++;
        }
    }
}
This entry was posted in 默认分类. Bookmark the permalink.