Java - try-with-resources Block

Introduction

Java try-with-resources works with a resource, such as a file, a SQL statement, etc.

Syntax

try (AnyResource aRes = create the resource...) {
    // Work with the resource here. The resource will be closed automatically.
}

The try-with-resources automatically closes the resources when the program exits the construct.

A try-with-resource construct may have one or more catch blocks and/or a finally block.

To use multiple resources in a try-with-resources block, separate them by a semicolon.

The following snippet of code shows some usage of try-with-resources to use one and multiple resources:

try (AnyResource aRes1 = getResource1()) {
   // Use aRes1 here
}

try (AnyResource aRes1 = getResource1(); AnyResource aRes2 = getResource2()) {
   // Use aRes1 and aRes2 here
}

The resources in a try-with-resources are implicitly final.

try (final AnyResource aRes1 = getResource1()) {
        // Use aRes1 here
}

AutoCloseable interface

A resource in a try-with-resources must be of the type java.lang.AutoCloseable.

The AutoCloseable interface has a close() method.

When exiting the try-with-resources block, the close() method of all the resources is called automatically.

For multiple resources, the close() method is called in the reverse order in which the resources are specified.

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 a va2 s  .  c  om*/

  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, false)) {
      mr.use();
      mr.use();
    }
  }
}

Result

Related Topics