Try-with-Resources: jdk8 vs jdk9

Till Java 7:

Until Java 7, if we use any closeable resource inside try block, we need to explicitly close the resource inside the finally block.

FileOutputStream fileOutputStream = null;
try {
  fileOutputStream = new FileOutputStream("file.txt");
  String message = "Try-with-resources example";
  fileOutputStream.write(message.getBytes());
  System.out.println("Success!!");
} catch (FileNotFoundException fne) {
  System.out.println("FileNotFoundException occurred while writing "
      + "to the file.");
} catch (IOException ioe) {
  System.out.println("IOException occurred while writing "
      + "to the file.");
} finally {
  try {
    if (fileOutputStream != null) {
      fileOutputStream.close();
    }
  } catch (IOException ioe) {
    System.out.println("Exception occurred while closing "
        + "the fileOutputStream.");
  }
}

If we forget to close the resource, it can cause resource leaking or lead to unintended behavior of the code.

Java 8:

jdk8 has introduced a new feature called Try-with-Resources. If a class (or any superclass of the given class) implements AutoCloseable interface, we can simply create the object of the class inside try() and jdk will automatically call close() method of the class, removing the need of finally block.

try (FileOutputStream fileOutputStream = new FileOutputStream("file.txt")) {
  String message = "Try-with-resources example";
  fileOutputStream.write(message.getBytes());
  System.out.println("Success!!");
} catch (FileNotFoundException fne) {
  System.out.println("Exception occurred while writing "
      + "to the file.");
} catch (IOException ioe) {
  System.out.println("Exception occurred while writing "
       + "to the file.");
}

This made code cleaner and less error prone. But it can be only used with the object created inside try(). If for some reason the object is required outside the try block, it will not be accessible. Also, if the object needs to be accepted as parameter from another method, we will have to use the traditional try block with finally(as we were doing till Java 7) to achieve the requirement.

Java 9:

With Java 9, we do not need to create the object inside try(). It can use the objects created outside the try() or coming as parameter from calling method.

public static void main(String[] args) {
    try {
      FileOutputStream outputStream = new FileOutputStream("file.txt");
      writeFile(outputStream);
    } catch (FileNotFoundException fne) {
      System.out.println("FileNotFoundException occurred while writing "
          + "to the file.");
    }
  }

  public static void writeFile(FileOutputStream outputStream) {
    try {
      String message = "Try-with-resources example";
      outputStream.write(message.getBytes());
      System.out.println("Success!!");
    } catch (IOException ioe) {
      System.out.println("IOException occurred while writing "
          + "to the file.");
    }
  }