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

  1. Use finally for cleanup
  2. Or try-with-resources
  3. Handle cleanup errors separately

Related Exception Handling exercises

Practice all Exception Handling exercises · Run this idea in the Java compiler