-
Notifications
You must be signed in to change notification settings - Fork 0
The finally Block
The finally block always executes when the try block exits. This ensures that the finally block is executed even if an unexpected exception occurs. But finally is useful for more than just exception handling — it allows the programmer to avoid having cleanup code accidentally bypassed by a return, continue, or break. Putting cleanup code in a finally block is always a good practice, even when no exceptions are anticipated.
当 try 代码块退出时,finally 代码块总会执行。这确保了即使在有异常发生时,finally 代码块也会被执行。但是 finally 不仅仅是用来处理异常 -- 它可以避免程序中的清理代码因为 return, continue, 或者 break 语句而意外跳过不执行。将清理用的代码放到一个 finally 代码块中总是一个好的做法,及是没有异常会发生。
Note: If the JVM exits while the try or catch code is being executed, then the finally block may not execute. Likewise, if the thread executing the try or catch code is interrupted or killed, the finally block may not execute even though the application as a whole continues.
注意:如果在 try 或者 catch 代码被执行后 JVM 退出了,finally 代码块可能不会被执行。同样的,如果一个执行 try 或者 catch 代码的线程被中断或者杀掉,finally 代码块也可能不会执行,即使整个程序还在继续执行。
The try block of the writeList method that you've been working with here opens a PrintWriter. The program should close that stream before exiting the writeList method. This poses a somewhat complicated problem because writeList's try block can exit in one of three ways.
再前面的代码中,writeList 方法中的 try 代码块打开了一个 PrintWriter。程序应该在退出 writeList 方法前关闭这个流。这造成了一个有点复杂的问题,因为 writeList 的 try 代码块已下面三种方式退出。
-
The new FileWriter statement fails and throws an IOException.
-
The list.get(i) statement fails and throws an IndexOutOfBoundsException.
-
Everything succeeds and the try block exits normally.
-
new FilterWriter 语句执行失败并抛出一个 IOException。
-
list.get(i) 语句执行失败并抛出一个 IndexOutOfBoundsException。
-
一切执行正常,try 代码块正常退出。
The runtime system always executes the statements within the finally block regardless of what happens within the try block. So it's the perfect place to perform cleanup.
无论 try 代码块中的代码发生什么,系统总会执行 finally 代码块中的语句。所以这是一个进行清理的完美地方。
The following finally block for the writeList method cleans up and then closes the PrintWriter.
下面 writeList 方法的 finally 代码块清理并关闭了 PrintWriter。
finally {
if (out != null) {
System.out.println("Closing PrintWriter");
out.close();
} else {
System.out.println("PrintWriter not open");
}
}
Important: The finally block is a key tool for preventing resource leaks. When closing a file or otherwise recovering resources, place the code in a finally block to ensure that resource is always recovered.
重点:finally 代码块是防止资源泄漏的关键。当需要关闭一个文件或者其他需要恢复的资源时,将代码放到 finally 代码块中确保资源总会被恢复。
Consider using the try-with-resources statement in these situations, which automatically releases system resources when no longer needed. The The try-with-resources Statement section has more information.
考虑在这种情况下使用 try-with-resources 语句,他会在资源不再需要的时候自动将其释放。下面的 try-with-resource 语句章节会有更多信息。