Thursday, 4 May 2023

Try With Resources Improvement in Java 9

We know, Java SE 7 has introduced a new exception-handling construct: Try-With-Resources to manage resources automatically. The main goal of this new statement is “Automatic Better Resource Management”. Java SE 9 is going to provide some improvements to this statement to avoid some more verbosity and improve some Readability.



Consider the example below. When the try block ends the resources are automatically released. We do not need to create a separate finally block.

Java SE 7 example

public static void main(String[] args) {
//Cannot access the 'br' BufferedReader object outside the try block
try (BufferedReader br = new BufferedReader(new FileReader("FILE_PATH")))
{
String line;
while((line = br.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
}

How does try with resources work?

try-with-resources is available to any class that implements the AutoCloseable interface. In the above example, BufferedReader implements an AutoCloseable interface.

public interface AutoCloseable {
void close() throws Exception;
}

Java 9 example

public static void main(String[] args) throws FileNotFoundException {
//Access the 'br' BufferedReader object outside the try block
BufferedReader br = new BufferedReader(new FileReader("FILE_PATH"));
try (br)
{
String line;
while((line = br.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
}

No comments:

Post a Comment