Junior — Middle
What are the advantages and disadvantages of using try-with-resources for automatic resource management?
sobes.tech AI
Answer from AI
The try-with-resources construct in Java automatically closes resources that implement the AutoCloseable interface after the try block completes.
Advantages:
- Reduces boilerplate code for closing resources.
- Eliminates the risk of forgetting to close a resource, reducing leaks.
- Exception handling during resource closing is automatic and correct.
Disadvantages:
- Only works with resources that implement
AutoCloseable. - In some cases, it may be less flexible if complex closing logic is required.
Example:
try (BufferedReader br = new BufferedReader(new FileReader("file.txt"))) {
String line = br.readLine();
System.out.println(line);
} // br is automatically closed here