Java try-with-resources Complete Guide
In Java, try-with-resources is a syntax structure used to automatically close resources at the end of a code block. This ensures that open resources like files, network connections, and database connections are properly closed when the program ends.
The syntax for using try-with-resources is:
try (资源的声明) {
// 代码块
} catch (异常类型 变量) {
// 异常处理
}
The declaration part of resources needs to implement the AutoCloseable interface so that the close() method of the resource will be automatically called to close the resource when the code block ends. After the try block is completed, regardless of whether an exception occurs, the resource will be automatically closed.
For example, the code using try-with-resources to read the content of a file is as follows:
try (BufferedReader br = new BufferedReader(new FileReader("file.txt"))) {
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
In this example, the BufferedReader will automatically close after the try block has finished executing, so there is no need to manually call the close() method. If an IO exception occurs while reading the file, the catch block will catch and handle the exception.