Sobes.tech
Junior — Middle

Как работает конструкция try-with-resources и для чего она предназначена?

sobes.tech AI

Answer from AI

The try-with-resources construct in Java is designed for automatic closing of resources that implement the AutoCloseable interface (such as input-output streams, database connections). It guarantees that the resource will be closed immediately after the try block completes, even if an exception occurs inside.

Example of usage:

try (BufferedReader reader = new BufferedReader(new FileReader("file.txt"))) {
    String line = reader.readLine();
    System.out.println(line);
} catch (IOException e) {
    e.printStackTrace();
}

In this example, reader will automatically close after exiting the try block, eliminating the need to explicitly call reader.close() in a finally block.