Documentation

The Java™ Tutorials
Hide TOC
The finally Blockfinally块
Trail: Essential Java Classes
Lesson: Exceptions
Section: Catching and Handling Exceptions

The finally Blockfinally块

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块中始终是一种好的做法,即使在没有预期异常的情况下也是如此。


Note: If the JVM exits while the try or catch code is being executed, then the finally block may not execute.如果JVM在执行trycatch代码时退出,那么finally块可能不会执行。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.同样,如果执行trycatch代码的线程被中断或终止,那么即使整个应用程序继续运行,finally块也可能不会执行。

The try block of the writeList method that you've been working with here opens a PrintWriter.您在此处使用的writeList方法的try块将打开一个PrintWriterThe 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.这带来了一个有点复杂的问题,因为writeListtry块可以通过以下三种方式之一退出。

  1. The new FileWriter statement fails and throws an IOException.new FileWriter语句失败并引发IOException
  2. The list.get(i) statement fails and throws an IndexOutOfBoundsException.list.get(i)语句失败并抛出IndexOutOfBoundsException
  3. Everything succeeds and the 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");
    } 
}

Important: The finally block is a key tool for preventing resource leaks.finally块是防止资源泄漏的关键工具。When closing a file or otherwise recovering resources, place the code in a finally block to ensure that resource is always recovered.关闭文件或以其他方式恢复资源时,请将代码放在finally块中,以确保始终恢复资源。

Consider using the try-with-resources statement in these situations, which automatically releases system resources when no longer needed.考虑在这些情况下使用try-with-resources语句,在不再需要时自动释放系统资源。The The try-with-resources Statement section has more information.try-with-resources语句部分包含更多信息。

Previous page: The catch Blocks
Next page: The try-with-resources Statement