我们可以在finally块中使用“return”

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

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

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

根据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). 

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

是的,您可以在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总是执行是否存在exception。 所以当finally块运行时,它将覆盖其他的返回值。 在finally块中写入return语句不是必需的,实际上你不应该写它。

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

最后,它不仅仅用于exception处理 – 它允许程序员避免因返回,继续或中断而意外绕过清理代码。 将清理代码放在finally块中总是一种很好的做法,即使没有预期的例外情况也是如此。

不建议在其中编写逻辑。

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

我们假设你有这个function

 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