Java 异常中的 return 语句

513 阅读1分钟

Java 异常中,finally 中的代码块由 JVM 来确保无论 try 中的语句是否由异常,都会被执行。那如果 finally 代码块中包含 return 语句的话,执行逻辑会是怎样的?

try 和 finally 中的 return

public class ExceptionExample {
    private static String test() {
        String step = "";
        try {
            int result = 1/1;
            return step += ",try";
        } catch (Exception e) {
            return step += ",catch";
        } finally {
            return step += ",finally";
        }
    }

    public static void main(String[] args) {
        System.out.printf("return order: %s", test());
    }
}

执行结果

return order: ,try,finally

catch 和 finally 中的 return

public class ExceptionExample {
    private static String test() {
        String step = "";
        try {
            int result = 1/0;
            return step += ",try";
        } catch (Exception e) {
            return step += ",catch";
        } finally {
            return step += ",finally";
        }
    }

    public static void main(String[] args) {
        System.out.println(test());
    }
}

执行结果

return order: ,catch,finally

从上面的两个示例中可以看出,如果 finally 中存在 return 语句,return 的执行逻辑如下:

  1. 执行 try 和 catch 中 return 语句后的表达式;
  2. 执行 finally 中 return 语句后的表达式;
  3. 执行 finally 中 return 语句;