在 Java 中是否总是执行 finally 块?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/65035/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 07:51:07  来源:igfitidea点击:

Does a finally block always get executed in Java?

javaerror-handlingreturntry-catch-finally

提问by jonny five

Considering this code, can I be absolutely surethat the finallyblock always executes, no matter what something()is?

考虑到这段代码,我可以绝对确定finally块始终执行,无论是什么something()

try {  
    something();  
    return success;  
}  
catch (Exception e) {   
    return failure;  
}  
finally {  
    System.out.println("I don't know if this will get printed out");
}

采纳答案by jodonnell

Yes, finallywill be called after the execution of the tryor catchcode blocks.

是的,finally将在执行trycatch代码块后调用。

The only times finallywon't be called are:

唯一finally不会被调用的时间是:

  1. If you invoke System.exit()
  2. If you invoke Runtime.getRuntime().halt(exitStatus)
  3. If the JVM crashes first
  4. If the JVM reaches an infinite loop (or some other non-interruptable, non-terminating statement) in the tryor catchblock
  5. If the OS forcibly terminates the JVM process; e.g., kill -9 <pid>on UNIX
  6. If the host system dies; e.g., power failure, hardware error, OS panic, et cetera
  7. If the finallyblock is going to be executed by a daemon thread and all other non-daemon threads exit before finallyis called
  1. 如果你调用 System.exit()
  2. 如果你调用 Runtime.getRuntime().halt(exitStatus)
  3. 如果 JVM 先崩溃
  4. 如果 JVM 在tryorcatch块中到达无限循环(或其他一些不可中断、非终止的语句)
  5. 如果操作系统强行终止JVM进程;例如,kill -9 <pid>在 UNIX 上
  6. 如果主机系统死机;例如,电源故障、硬件错误、操作系统恐慌等
  7. 如果finally块将由守护线程执行并且所有其他非守护线程在finally调用之前退出

回答by shyam

finally is always executed unless there is abnormal program termination (like calling System.exit(0)..). so, your sysout will get printed

finally 总是执行,除非程序异常终止(比如调用 System.exit(0)..)。所以,你的系统输出会被打印出来

回答by Mendelt

Yes it will get called. That's the whole point of having a finally keyword. If jumping out of the try/catch block could just skip the finally block it was the same as putting the System.out.println outside the try/catch.

是的,它会被调用。这就是拥有 finally 关键字的全部意义所在。如果跳出 try/catch 块可以跳过 finally 块,这与将 System.out.println 放在 try/catch 之外是一样的。

回答by Kevin

Example code:

示例代码:

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

public static int test() {
    try {
        return 0;
    }
    finally {
        System.out.println("finally trumps return.");
    }
}

Output:

输出:

finally trumps return. 
0

回答by Scott Dorman

That's actually true in any language...finally will always execute before a return statement, no matter where that return is in the method body. If that wasn't the case, the finally block wouldn't have much meaning.

这实际上在任何语言中都是正确的...finally 将始终在 return 语句之前执行,无论该 return 在方法体中的哪个位置。如果不是这种情况,finally 块就没有多大意义。

回答by user9189

The finally block is always executed unless there is abnormal program termination, either resulting from a JVM crash or from a call to System.exit(0).

除非由于 JVM 崩溃或调用System.exit(0).

On top of that, any value returned from within the finally block will override the value returned prior to execution of the finally block, so be careful of checking all exit points when using try finally.

最重要的是,从 finally 块中返回的任何值都将覆盖在执行 finally 块之前返回的值,因此在使用 try finally 时要小心检查所有退出点。

回答by MooBob42

Also, although it's bad practice, if there is a return statement within the finally block, it will trump any other return from the regular block. That is, the following block would return false:

此外,虽然这是不好的做法,但如果 finally 块中有 return 语句,它将胜过来自常规块的任何其他 return。也就是说,以下块将返回 false:

try { return true; } finally { return false; }

Same thing with throwing exceptions from the finally block.

从 finally 块中抛出异常也是如此。

回答by James A. N. Stauffer

Also a return in finally will throw away any exception. http://jamesjava.blogspot.com/2006/03/dont-return-in-finally-clause.html

此外,finally 中的返回将丢弃任何异常。 http://jamesjava.blogspot.com/2006/03/dont-return-in-finally-clause.html

回答by Garth Gilmour

A logical way to think about this is:

考虑这一点的合乎逻辑的方法是:

  1. Code placed in a finally block must be executed whatever occurswithin the try block
  2. So if code in the try block tries to return a value or throw an exception the item is placed 'on the shelf' till the finally block can execute
  3. Because code in the finally block has (by definition) a high priority it can return or throw whatever it likes. In which case anything left 'on the shelf' is discarded.
  4. The only exception to this is if the VM shuts down completely during the try block e.g. by 'System.exit'
  1. 放置在 finally 块中的代码必须在 try 块中发生任何事情中执行
  2. 因此,如果 try 块中的代码试图返回一个值或抛出异常,则该项目将被放置在“货架上”,直到 finally 块可以执行
  3. 因为 finally 块中的代码(根据定义)具有高优先级,它可以返回或抛出任何它喜欢的东西。在这种情况下,任何留在“架子上”的东西都会被丢弃。
  4. 唯一的例外是如果 VM 在 try 块期间完全关闭,例如通过“System.exit”

回答by Alex Miller

In addition to the point about return in finally replacing a return in the try block, the same is true of an exception. A finally block that throws an exception will replace a return or exception thrown from within the try block.

除了在最终替换 try 块中的 return 时关于 return 的要点之外,异常也是如此。抛出异常的 finally 块将替换从 try 块中抛出的返回或异常。