Create a resource that can be used with the try-with-resources technique in Java

Description

The following code shows how to create a resource that can be used with the try-with-resources technique.

Example


public class Main {
  public static void main(String[] args) {
    try (MyResource resource1 = new MyResource();
        OtherResource resource2 = new OtherResource()) {
      resource1.do1();/*from w w  w .  j  av  a2s.com*/
      resource2.do2();
    } catch (Exception e) {
      e.printStackTrace();
      for (Throwable throwable : e.getSuppressed()) {
        System.out.println(throwable);
      }
    }

  }
}

class MyResource implements AutoCloseable {

  @Override
  public void close() throws Exception {
    System.out.println("close method executed");
    throw new UnsupportedOperationException("A problem has occurred");
  }

  public void do1() {
    System.out.println("method executed");
  }
}

class OtherResource implements AutoCloseable {
  @Override
  public void close() throws Exception {
    System.out.println("A");
    throw new UnsupportedOperationException("A problem has occurred");
  }

  public void do2() {
    System.out.println("executed");
  }
}

The code above generates the following result.





















Home »
  Java Tutorial »
    Java Language »




Java Data Type, Operator
Java Statement
Java Class
Java Array
Java Exception Handling
Java Annotations
Java Generics
Java Data Structures