Sobes.tech
Senior

Как работает try-with-resources в Java?

sobes.tech AI

Answer from AI

The try-with-resources statement in Java is used for automatic closing of resources that implement the AutoCloseable interface (such as streams, database connections).

Syntax:

try (ResourceType resource = new ResourceType()) {
    // work with the resource
}

After the try block executes, the resource is automatically closed, even if an exception occurs inside the block. This simplifies resource management and prevents leaks.

Example:

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

Here, BufferedReader will be closed automatically after exiting the try block, without needing to explicitly call br.close() in finally.

Important features:

  • Multiple resources can be declared separated by semicolons.
  • If an exception occurs while closing a resource, it is added as suppressed to the main exception.
  • Improves code readability and reliability.