The Java Tutorials have been written for JDK 8.Java教程是为JDK 8编写的。Examples and practices described in this page don't take advantage of improvements introduced in later releases and might use technology no longer available.本页中描述的示例和实践没有利用后续版本中引入的改进,并且可能使用不再可用的技术。See Java Language Changes for a summary of updated language features in Java SE 9 and subsequent releases.有关Java SE 9及其后续版本中更新的语言特性的摘要,请参阅Java语言更改。
See JDK Release Notes for information about new features, enhancements, and removed or deprecated options for all JDK releases.有关所有JDK版本的新功能、增强功能以及已删除或不推荐的选项的信息,请参阅JDK发行说明。
The 当finally
block always executes when the try
block exits.try
块退出时,finally
块始终执行。This ensures that the 这确保即使发生意外异常,也会执行finally
block is executed even if an unexpected exception occurs.finally
块。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.finally
块中始终是一种好的做法,即使在没有预期异常的情况下也是如此。
try
or catch
code is being executed, then the finally
block may not execute.try
或catch
代码时退出,那么finally
块可能不会执行。try
or catch
code is interrupted or killed, the finally
block may not execute even though the application as a whole continues.try
或catch
代码的线程被中断或终止,那么即使整个应用程序继续运行,finally
块也可能不会执行。The 您在此处使用的try
block of the writeList
method that you've been working with here opens a PrintWriter
.writeList
方法的try
块将打开一个PrintWriter
。The program should close that stream before exiting the 程序应该在退出writeList
method.writeList
方法之前关闭该流。This poses a somewhat complicated problem because 这带来了一个有点复杂的问题,因为writeList
's try
block can exit in one of three ways.writeList
的try
块可以通过以下三种方式之一退出。
new FileWriter
statement fails and throws an IOException
.new FileWriter
语句失败并引发IOException
。list.get(i)
statement fails and throws an IndexOutOfBoundsException
.list.get(i)
语句失败并抛出IndexOutOfBoundsException
。try
block exits normally.try
块正常退出。The runtime system always executes the statements within the 运行时系统始终在finally
block regardless of what happens within the try
block.finally
块中执行语句,而不管try
块中发生了什么。So it's the perfect place to perform cleanup.所以这是进行清理的最佳场所。
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"); } }
finally
block is a key tool for preventing resource leaks.finally
块是防止资源泄漏的关键工具。finally
block to ensure that resource is always recovered.finally
块中,以确保始终恢复资源。try-
with-resources statement in these situations, which automatically releases system resources when no longer needed.try-
with-resources语句,在不再需要时自动释放系统资源。