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()).
Previous
What is the difference between List.of() and Arrays.asList()?
Next
What is PriorityQueue in Java?
More Java Questions
View all →- Intermediate What is the Java Collections Framework?
- Intermediate What is the difference between ArrayList and LinkedList?
- Intermediate What is HashMap in Java and how does it work internally?
- Intermediate What is the difference between HashMap and HashTable in Java?
- Intermediate What is the difference between HashMap and LinkedHashMap?