Java- Try With Resources

Reading Time: 2 minutes

In this blog, I would be talking about the Important topic of java which is try-with-resources. Many of us have used the try and catch blocks in our java codes multiple times. The support for try-with-resources introduced in java 7 but there was some limitations which java creaters overcome in java 9.

The try-with-resources statement is a try statement that declares one or more resources. A resource is an object that must be closed after the program is finished with it. The try-with-resources statement ensures that each resource is closed at the end of the statement. Any object that implements java.lang.AutoCloseable , which includes all objects which implement java.io.Closeable, can be used as a resource.

Let’s take a example of try-with-resources where we would be declare resource in the try block –

try (PrintWriter writer = new PrintWriter(new File("test.txt"))) {
    writer.println("Hello World");
}

Why?

One questions may be you can raise, why to use try-with-resources when we already have try-catch-finally, right? Let’s take a example –

public class Knoldus{
      static String readFile(String url) throws IOException {
             BufferedReader reader = new BufferedReader(new FileReader(url));
             try{
                 return reader.readLine();
             } finally {
                 reader.close();    
             }

    }
}

If there is any exception in the try block then finally block will ensure that resources, should be closed but if there is any exception occurred in the finally block. Suppose due to some unavailability of underlying hardware, resource was not acquired.This will throw an exception which will be handled but close() will also throw an exception. Now this exception will suppress the other exception which occurred before it. We would’t be able to find the reason of the second exception. This is the major issue which handled by using the try-with-resources.

Multiple Resources

We can declare multiple resource in the try-with-resources block by separating them with a semi column.

try (Scanner scanner = new Scanner(new File("Read.txt"));PrintWriter writer = new PrintWriter(new File("Write.txt"))) {
    while (scanner.hasNext()) {
	writer.print(scanner.nextLine());
    }
}

Ordering

If we defined multiple resources in the try-with-resources block then which resource will closed first/last? Let’s take a example for answering the question.

public class ResourcesFirst implements AutoCloseable {

    public ResourcesFirst() {
        System.out.println("Constructor -> Resources_First");
    }

    public void doSomething() {
        System.out.println("Something -> Resources_First");
    }

    @Override
    public void close() throws Exception {
        System.out.println("Closed Resources_First");
    }
}
public class ResourcesSecond implements AutoCloseable {

    public ResourcesSecond() {
        System.out.println("Constructor -> Resources_Second");
    }

    public void doSomething() {
        System.out.println("Something -> Resources_Second");
    }

    @Override
    public void close() throws Exception {
        System.out.println("Closed Resources_Second");
    }
}
try (ResourcesFirst af = new ResourcesFirst();
        ResourcesSecond as = new ResourcesSecond()) {

        af.doSomething();
        as.doSomething();
    }

Output –

Constructor -> Resources_First
Constructor -> Resources_Second
Something -> Resources_First
Something -> Resources_Second
Closed Resources_Second
Closed Resources_First

The resources which defined first in the try-with-resources will be close last during execution.

That’s pretty much it from the article. If you have any feedback or queries, please do let me know in the comments. Also, if you liked the article, please give me a thumbs up and I will keep writing blogs like this for you in the future as well. Keep reading and Keep coding.

Reference

Oracle reference


Knoldus-blog-footer-image


Written by 

Lokesh Aggarwal is a software Consultant trainee with 6 months of experience at Knoldus Inc.