Resource Cleanup Pattern in Java: Explanation & Practice
Ensure resources are cleaned up
Problem summary
Implement a pattern that ensures cleanup happens even if exception occurs.
Starter code
public class Main {
// Simulate resource operations
public static void main(String[] args) {
// Open resource
// Do work (may fail)
// Always close resource
}
}Expected output and test cases
- Cleanup after error
Opened Working... Error occurred Closed
- Cleanup after success
Opened Working... Success Closed
- Open failed
Failed to open Nothing to close
Hints
- Use finally for cleanup
- Or try-with-resources
- Handle cleanup errors separately
Related Exception Handling exercises
- Practice Password Validation in Java
- Practice Null Handling in Java
- Practice Exception Logging in Java
Practice all Exception Handling exercises · Run this idea in the Java compiler