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

  1. try (Resource r = new Resource())
  2. Resource must implement AutoCloseable
  3. close() called automatically

Related Exception Handling exercises

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