Java - try-with-resources Block with catch

Introduction

A try-with-resources block may throw an exception the close() method may also throw an exception.

If either of it happened, Java reports the exception thrown from the try-with-resources block.

Demo

class MyResource implements AutoCloseable {
  private int level;
  private boolean exceptionOnClose;

  public MyResource(int level, boolean exceptionOnClose) {
    this.level = level;
    this.exceptionOnClose = exceptionOnClose;
    System.out.println("Creating MyResource. Level = " + level);
  }/*from w  w w . j  av a  2 s . c  o m*/

  public void use() {
    if (level <= 0) {
      throw new RuntimeException("Low in level.");
    }
    System.out.println("Using MyResource level " + this.level);
    level--;
  }

  @Override
  public void close() {
    if (exceptionOnClose) {
      throw new RuntimeException("Error in closing");
    }
    System.out.println("Closing MyResource...");
  }
}

public class Main {
  public static void main(String[] args) {
    try (MyResource mr = new MyResource(2, true)) {
      mr.use();
      mr.use();
      mr.use(); // Will throw a RuntimeException
    } catch (Exception e) {
      System.out.println(e.getMessage());
    }

  }
}

Result

Related Topic