# 终于阻止了

> 原文： [https://docs.oracle.com/javase/tutorial/essential/exceptions/finally.html](https://docs.oracle.com/javase/tutorial/essential/exceptions/finally.html)

当`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.

* * *

您在此处使用的`writeList`方法的`try`块打开`PrintWriter`。程序应该在退出`writeList`方法之前关闭该流。这提出了一个有点复杂的问题，因为`writeList`的`try`块可以以三种方式之一退出。

1.  `new FileWriter`语句失败并抛出`IOException`。
2.  `list.get(i)`语句失败并抛出`IndexOutOfBoundsException`。
3.  一切都成功，`try`块正常退出。

无论`try`块中发生什么，运行系统总是执行`finally`块内的语句。所以这是进行清理的最佳地点。

`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.

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](tryResourceClose.html) section has more information.

* * *