我们可以在finally块中使用"return"

Rak*_* KR 38 java finally try-catch-finally

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

Ank*_*thi 46

finally块内返回将导致exceptions丢失.

finally块中的return语句将导致可能在try或catch块中抛出的任何异常被丢弃.

根据Java语言规范:

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

   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).
Run Code Online (Sandbox Code Playgroud)

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

  • 浏览以下代码http://ideone.com/AU9KvS。您尝试的例外被吃掉了。 (2认同)
  • 您应该在答案中添加"返回"被Java规范视为突然完成. (2认同)

Kru*_*hna 27

是的,您可以在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));
    }
}
Run Code Online (Sandbox Code Playgroud)

输出总是2,因为我们从finally块返回2.记住,finally总是执行是否存在异常.所以当finally块运行时,它将覆盖其他的返回值.在finally块中编写return语句不是必需的,实际上你不应该写它.


Sur*_*tta 6

是的,你可以,但你不应该 1 ,因为 finally 块是为了特殊目的。

finally 不仅仅用于异常处理——它允许程序员避免通过 return、continue 或 break 意外绕过清理代码。将清理代码放在 finally 块中始终是一个好习惯,即使没有预料到异常也是如此。

不建议在其中编写逻辑。