☕ Java Intermediate

What is try-with-resources in Java?

Answer

Try-with-resources (Java 7+) automatically closes resources that implement the AutoCloseable interface at the end of the try block, regardless of whether an exception is thrown. Before this feature, you had to close resources manually in finally blocks, which was verbose and error-prone. Example: try (BufferedReader br = new BufferedReader(new FileReader(file))) { return br.readLine(); }. The resource is closed automatically when the try block exits. Multiple resources can be declared: the last-declared resource is closed first. If both the try body and the close() method throw exceptions, the close() exception is suppressed (accessible via getSuppressed()).