What is try-with-resources in Java?

In Java, the try-with-resources statement is a feature that simplifies the management of resources like files, sockets, or database connections. Introduced in Java 7, this statement automatically closes resources that implement the AutoCloseable or Closeable interfaces when the try block finishes executing, either normally or due to an exception. This eliminates the need for explicit try-catch-finally blocks to clean up these resources, reducing boilerplate code and the risk of resource leaks.

Example of Try-with-Resources

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(); }

try-with-resources Java resource management AutoCloseable exception handling