Try-With-Resources in Java: Explanation & Practice
Automatic resource management
Problem summary
Demonstrate try-with-resources for automatic resource closing.
Starter code
import java.io.*;
public class Main {
public static void main(String[] args) {
// Use try-with-resources
// Simulate resource usage
// Print: Resource opened, Resource closed
}
}Expected output and test cases
- Auto close
Resource opened Resource closed
Hints
- try (Resource r = new Resource())
- Resource must implement AutoCloseable
- close() called automatically
Related Exception Handling exercises
- Practice Throwing Exceptions in Java
- Practice Using Throws Clause in Java
- Practice Custom Exception Class in Java
Practice all Exception Handling exercises · Run this idea in the Java compiler