Junior — Middle
What are the advantages and disadvantages of using try-with-resources in Java for resource management?
sobes.tech AI
Answer from AI
The try-with-resources statement in Java is used for automatic resource management. It ensures that each resource opened in the try block is closed automatically at the end of the block.
Advantages:
- Resources are closed automatically, reducing the risk of resource leaks.
- Code becomes cleaner and shorter, no need for explicit finally blocks.
- Exception handling is clearer, as suppressed exceptions are handled automatically.
Disadvantages:
- Works only with resources that implement AutoCloseable.
- Less flexible for complex resource management or custom cleanup logic.
Example:
try (BufferedReader br = new BufferedReader(new FileReader("file.txt"))) {
String line = br.readLine();
System.out.println(line);
} catch (IOException e) {
e.printStackTrace();
}
// br resource is automatically closed after try block