使用try-with-resource 的情况下,resource 进入catch 块或者 finally 块之前,已经关闭了吗

gongchengship / 2024-10-08 / 原文

在 Java 中,使用 try-with-resources 的情况下,资源会在 try 块执行完毕后自动关闭。具体来说,无论是否发生异常,资源总是在控制流进入 catchfinally 块之前关闭

关键点:

  1. try-with-resources 是在 try 语句中声明和管理实现了 AutoCloseable 接口的资源,例如 InputStreamOutputStreamConnection 等。
  2. try 块执行完毕后,无论是正常结束还是抛出异常,资源都会在进入 catchfinally 块之前自动关闭。
  3. 如果抛出了异常,资源的关闭操作会在 catch 块之前进行。因此,当进入 catch 块时,资源已经被安全关闭了。

执行顺序:

  • 正常执行try 块中的代码执行完毕,资源被关闭,然后进入 finally 块(如果有)。
  • 异常情况:当 try 块中抛出异常,资源依然会在异常传播到 catch 块之前关闭。

示例代码:

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class TryWithResourcesExample {

    public static void main(String[] args) {
        try (BufferedReader reader = new BufferedReader(new FileReader("example.txt"))) {
            // 读取文件
            String line = reader.readLine();
            System.out.println(line);
            // 假设这里发生了异常
            throw new RuntimeException("Exception in try block");
        } catch (Exception e) {
            // 进入 catch 块之前,资源已经关闭
            System.out.println("Exception caught: " + e.getMessage());
        } finally {
            System.out.println("Finally block executed");
        }
    }
}

执行流程:

  1. try 块中打开文件并读取一行。
  2. 如果 try 块中发生异常(例如 throw new RuntimeException),BufferedReader 会在异常抛出并传播到 catch 块之前被关闭。
  3. 异常被捕获后,进入 catch 块处理异常。
  4. 最后执行 finally 块。

输出:

Exception caught: Exception in try block
Finally block executed

说明:

  • 当异常抛出时,资源 BufferedReader 会在进入 catch 块之前被关闭。
  • 即使 try 块中没有异常,资源也会在 try 块执行完毕后关闭,然后再进入 finally 块。

总结:

  • 资源总是在进入 catch 块或 finally 块之前关闭,这意味着你不需要在 catchfinally 块中手动关闭资源。
  • 这就是 try-with-resources 的优势,确保资源可以自动、安全地关闭,不论是否发生异常。