1. Introduction
In this article, we will present the try-with-resources
statement introduced in Java 7. This special feature ensures that every resource will be closed at the end of the statement. In this tutorial, we will present the old way to deal with closing resources before Java 7, and gives some example that will show the advantage of this modern solution.
2. Cleanup resources the old way
Let's start with the example of closing resources before Java 7.
In applications with many IO operations, this kind of code fragment is very common. The problem is we need to add the finally
block every time we have to clean up the resources. This is not enough, because often close(...)
methods also throw an exception, so we need to add a try-catch statement in this finally
block. The code is getting even uglier when we have more than one resource to handle.
3. Using try-with-resources from Java 7
The sample program that reads a file from /tmp/test.txt
path using try-with-resources
statement will look like the following:
Here we used try
condition with brackets where we put resources that need to be closed BufferedReader
.
Java 7 introduced a new interface java.lang.AutoCloseable
with a single method close()
. Every AutoCloseable
resource in try-with-resource block will be closed by calling that method by JVM when the resource is no longer needed, practically right after block ends.
4. Creating custom AutoCloseable
object
This sample program will demonstrate how closing resources in try-with-resources
statement works:
The CustomAutoCloseable
class implements AutoCloseable
interface. In order to implement it correctly we implemented close()
method.
Running this code will present the following output:
but what will happen when we throw an exception in start()
method like in the following example:
the output will be:
In this case close()
method was also called even when an exception occurs. This is because it works like a finally
statement.
5. Conclusion
In this article, we presented how to use the try-with-resources
statement in Java. Before version 7 of Java, we had to use the finally
blocks to clean up the resources. Java 7 gives the opportunity to automatically close the resources that implemented the AutoCloseable
interface. Cleanup is initialized by JVM by calling the close()
method as soon as the try-with-resources
block finishes.
{{ 'Comments (%count%)' | trans {count:count} }}
{{ 'Comments are closed.' | trans }}