Java 9 Improved try-with-resources
try-with-resources is a new exception handling mechanism introduced in JDK 7, which makes it easy to close resources used within a try-catch block. 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 that implement java.io.Closeable, can be used as a resource.
The try-with-resources declaration has been improved in JDK 9. If you already have a resource that is a final or effectively final variable, you can use that variable in a try-with-resources statement without declaring a new variable in the try-with-resources statement.
Example
import java.io.BufferedReader;
import java.io.IOException;
import java.io.Reader;
import java.io.StringReader;
public class Tester {
public static void main(String[] args) throws IOException {
System.out.println(readData("test"));
}
static String readData(String message) throws IOException {
Reader inputString = new StringReader(message);
BufferedReader br = new BufferedReader(inputString);
try (BufferedReader br1 = br) {
return br1.readLine();
}
}
}
Output:
test
In the above example, we need to declare the resource br1 in the try block before we can use it.
In Java 9, we can use br without declaring it and get the same result.
Example
import java.io.BufferedReader;
import java.io.IOException;
import java.io.Reader;
import java.io.StringReader;
public class Tester {
public static void main(String[] args) throws IOException {
System.out.println(readData("test"));
}
static String readData(String message) throws IOException {
Reader inputString = new StringReader(message);
BufferedReader br = new BufferedReader(inputString);
try (br) {
return br.readLine();
}
}
}
Output:
test
When dealing with resources that must be closed, use the try-with-resources statement instead of the try-finally statement. The resulting code is more concise and clearer, and the exceptions produced are more useful. The try-with-resources statement makes it easier to write code that must close resources without errors, which is practically impossible with the try-finally statement.