【问题标题】:Can we use "return" in finally block [duplicate]我们可以在 finally 块中使用“return”吗?
【发布时间】:2013-08-14 20:33:42
【问题描述】:

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

【问题讨论】:

标签: java exception try-catch-finally finally


【解决方案1】:

finally 块内部返回将导致exceptions 丢失。

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

根据Java Language Specification:

如果 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).

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

【讨论】:

  • JLS 引用不支持您关于 finally 块内的 return 语句的说法?
  • JLS 中的这些行用于异常,但对于 return 语句也是如此。
  • 我仍然没有得到引用和你的语句之间的关系——所以我写了a piece of code 这表明,当 finally 块包含 return 语句时,从 catch 块抛出的异常被吃掉了,但是从 try 块抛出的那些被抓住了。请验证。
  • 通过此代码ideone.com/AU9KvS 。你的尝试异常被吃掉了。
  • 您应该在答案中添加 return 被 Java 规范视为突然完成。
【解决方案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。请记住,无论是否有异常,finally 总是执行。因此,当 finally 块运行时,它将覆盖其他块的返回值。在 finally 块中不需要写 return 语句,实际上你不应该写。

【讨论】:

  • 你能解释一下吗?
  • try{ throws new exception(); } catch{ 抛出新异常();} finally{ 返回 5; } 这里发生了什么???
  • @Rakesh 它返回5
  • 如果 System.exit(0) 调用是从 try 或 catch 块完成的,它可能无法正常工作。在这种情况下,控件不会进入 finally 块。
  • System.exit(0) 阻止 finally 块的执行,因为 JVM 将要关闭,无论返回什么
【解决方案3】:

是的,你可以,但你不应该 1 ,因为the finally block 是为特殊目的而设计的。

finally 不仅仅用于异常处理——它允许程序员避免清理代码被 return、continue 或 break 意外绕过。将清理代码放在 finally 块中始终是一种很好的做法,即使在没有预期异常的情况下也是如此。

不推荐在里面写你的逻辑。

【讨论】:

【解决方案4】:

您可以在finally 块中编写return 语句,但从try 块返回的值将在堆栈上更新,而不是finally 块返回值。

假设你有这个功能

private Integer getnumber(){
Integer i = null;
try{
   i = new Integer(5);
   return i;
}catch(Exception e){return 0;}
finally{
  i = new Integer(7);
  System.out.println(i);
}
}

你是从 main 方法调用它

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

这会打印出来

7
5

【讨论】:

  • 问题是我们是否可以从 finally 块中返回一个值。请记住,finally 中的 return 语句将覆盖其他返回值。考虑下面的代码 sn-p: class ReturnClass { public int testValue() { try { return 3; } catch(Exception e) { } finally { return 5; } } public static void main(String ar[]) { ReturnClass rc = new ReturnClass(); System.out.println(rc.testValue());} } 输出将始终为 5。
  • 这是题外话。这让我很困惑,直到我仔细读到你不是 return 来自 finally 的控件,而只是从那里打印一些东西。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-06-04
  • 1970-01-01
  • 2010-12-09
  • 1970-01-01
  • 1970-01-01
  • 2011-10-18
  • 1970-01-01
相关资源
最近更新 更多