try-with-resources in Java

For Java 11 Certification Exam Practice Questions, refer http://talks.skilltoz.com/java-11-certification-exam-questions/

In this article, let us discuss the support for try-with-resources statement in Java, from the Java 11 certification perspective.

What is the try-with-resources statement?

The try-with-resources statement is try statement that ensures that all the resources declared in it are closed at the end of the try block. Any object that implements java.lang.AutoCloseable, which includes all objects which implement java.io.Closeable, can be used as a resource.

Let us look at an example.

public static void main(String[] args) {
  System.out.println("Enter an integer");
  try (Scanner scanner = new Scanner(System.in)) {
     System.out.println("int: " + scanner.nextInt());
  } catch (Exception e) {
     System.out.println("Exception "+e.getMessage());
  }
}

In this example, the resource declared in the try-with-resources statement is a Scanner. The declaration statement appears within parentheses immediately after the try keyword. The class Scanner implements the interface java.lang.AutoCloseable. As the Scanner object is declared in a try-with-resource statement, it will be closed regardless of whether the try statement completes normally or abruptly due to an exception.

Can you declare multiple resources in a try-with-resources block?

Yes, You can open two resources in the try block and semicolon can be used to separate the resource declaration statements. Here is an example.

public static void main(String[] args) {
   try (Scanner scanner = new Scanner(System.in); 
        PrintWriter writer = new PrintWriter(new 
        File("test.txt"))) {
        while (scanner.hasNext()) {
		writer.print(scanner.nextLine());
        }
    } catch (Exception e) {
	System.out.println("Exception " + e.getMessage());
    }
}

In the above example, a Scanner and a PrintWriter have been declared (separated with a semicolon) for use in the try block. These resources are automatically closed when the try block ends.

Can you have try-with-resources statements without any explicit catch or finally blocks?

A try-with-resources statement can have catch and finally blocks just like an ordinary try statement. However, these are optional because internally a finally block is provided even if you have added none. So, the below code is perfectly legal.

public static void main(String[] args) {
	System.out.println("Enter an integer");
	try (Scanner scanner = new Scanner(System.in)) {
	  System.out.println("int: " + scanner.nextInt());
	} 
}

In the above example, there is no catch or finally block. However, you need to provide the catch block if you want to handle the exception. Please note that any catch or finally block provided will be run after the resources declared have been closed.

What is the improvement made to try-with-resources in Java 9?

If we have resources that are already declared outside the try-with-resource Statement as final or effectively final, we had to redeclare them within the try block as shown below, before Java 9.

try (Resource r1 = resource1; Resource r2 = resource2) {
            ...
}

Now, it is not required. You can simply write as shown below.

  try (resource1; resource2) {
            ...
   }

References

For more information on this topic, you can refer https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html

Leave a Reply

Your email address will not be published. Required fields are marked *