Java try with resources

Published On: 2021/06/28

java |
Photo by zhenhappy on Unsplash

When we started learning Java back in 2000, we were asked to close the resources in the finally block or in the catch block before the method exits from the execution stack. This had been considered as a good practice until the option to use try-with-resources was introduced in Java 7. Will it work with all resources?

Try-with-resources construct closes those resources that implements AutoCloseable interface. The close method implemented in the implementation class handles the closing of the resource.

In the days of Java 5 we used to write the code which consumed the underline IO resources and it was mostly written as given below:

String read(String path) {    
    BufferedReader reader = null;
    try {
        reader = new BufferedReader(new FileReader(path));
        return reader.readLine();
    }catch(IOException ioe) {
      
      // Exception handling

      return null;
    }finally {
      if(reader != null){
        try {
          reader.close();
        }catch (IOException exp) {
          // Exception handling
          reader = null;
        }        
      }        
    }
    return null;
}

This code is bit cumbersome and new developers would say it is verbose.

Java 7

Thanks to java team for providing the feature try-with-resources which could close the resource that is enclosed in the try sphere

String read(String path) throws IOException {
    try (BufferedReader reader = new BufferedReader(new FileReader(path))) {
        return reader.readLine();
    }
}

try-with-resources statement allows us to create mutiple resources. We have to separate it using the semicolon.

try (Scanner scanner = new Scanner(new File("mobile-games.csv"));
    PrintWriter writer = new PrintWriter(new File("games-statistics.csv"))) {
    while (scanner.hasNext()) {
	    writer.print(scanner.nextLine());
    }
}

Java 9

When java 9 released, the try-with-resources statement accepts the variables of resources created outside of it. This makes the code simple and increase the readability.

final Scanner scanner = new Scanner(new File("mobile-games.csv"));
final PrintWriter writer = new PrintWriter(new File("games-statistics.csv"));
try (scanner;writer) {
    while (scanner.hasNext()) {
	    writer.print(scanner.nextLine());
    }
}

Closing Resource

In case we use mutiple resources inside the try-with-resources statement, the order of closing is in the reverse order. The resource created last will be closed first and the first resource will be closed last.

Suppressed Exceptions

There is a chance that the try-with-resources could throw exception due to an exception which occured in the try block. In such cases the exception thrown from the try-with-resources could be suppressed and the exception propogated outside is the one from try block. We could fetch the suppressed exception by calling Throwable.getSuppressed() method from the exception thrown by the try block.

Conclusion

This article is written to give an idea on how to use the try-with-resources statement for those who are already using java version 7 or later.

comments powered by Disqus