我们可以在“最终块”中使用“返回”吗?

2022-08-31 17:28:42

我们可以在 finally block 中使用 return 语句吗?这会导致任何问题吗?


答案 1

从块内部返回将导致丢失。finallyexceptions

finally 块中的 return 语句将导致丢弃在 try 或 catch 块中可能引发的任何异常。

根据 Java 语言规范:

如果由于任何其他原因R突然完成try块的执行,则执行最终块,然后有一个选择:

   If the finally block completes normally, then the try statement
   completes  abruptly for reason R.

   If the finally block completes abruptly for reason S, then the try
   statement  completes abruptly for reason S (and reason R is
   discarded).

注意:根据 JLS 14.17 - 返回语句总是突然完成。


答案 2

是的,您可以在 finally 块中写入 return 语句,它将覆盖其他返回值。

编辑:
例如在下面的代码中

public class Test {

    public static int test(int i) {
        try {
            if (i == 0)
                throw new Exception();
            return 0;
        } catch (Exception e) {
            return 1;
        } finally {
            return 2;
        }
    }

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

输出始终为 2,因为我们从 finally 块返回 2。请记住,无论是否存在异常,finalal 始终执行。因此,当最终块运行时,它将覆盖其他块的返回值。在 finally block 中编写返回语句不是必需的,事实上你不应该写它。