Sobes.tech
Junior — Middle

What is the purpose of the try-with-resources construct in Java?

sobes.tech AI

Answer from AI

The try-with-resources construct in Java is used for automatically closing resources that implement the AutoCloseable interface (such as files, streams, database connections). This prevents resource leaks, as the resource is guaranteed to be closed after the try block executes, even if an exception occurs.

Example:

try (BufferedReader br = new BufferedReader(new FileReader("file.txt"))) {
    String line = br.readLine();
    System.out.println(line);
} catch (IOException e) {
    e.printStackTrace();
}
// Here, br is automatically closed after the try block
What is the purpose of the try-with-resources… - sobes.tech