Today we will look into Java Try with Resources. One of the Java 7 feature is try-with-resources statement for automatic resource management.
Try with Resources
A resource is an object that must be closed once your program is done using it. For example, a File resource or JDBC resource for a database connection or a Socket connection resource. Before Java 7, there was no auto resource management and we should explicitly close the resource once our work is done with it. Usually, it was done in the finally
block of a try-catch
statement. This approach used to cause memory leaks and performance hit when we forgot to close the resource.
Let’s see a pseudo code snippet to understand this java try with resources feature.
Before Java 7:
1 2 3 4 5 6 7 8 9 |
try{ //open resources like File, Database connection, Sockets etc } catch (FileNotFoundException e) { // Exception handling like FileNotFoundException, IOException etc }finally{ // close resources } |
Java 7 try with resources implementation:
1 2 3 4 5 6 7 8 |
try(// open resources here){ // use resources } catch (FileNotFoundException e) { // exception handling } // resources are closed as soon as try-catch block is executed. |
Let’s write a simple program to read a file and print the first line using Java 6 or older versions and Java 7 try-with-resources implementation.
Java 6 Resource Management Example
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
package com.journaldev.util; import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; public class Java6ResourceManagement { public static void main(String[] args) { BufferedReader br = null; try { br = new BufferedReader(new FileReader("C:\journaldev.txt")); System.out.println(br.readLine()); } catch (IOException e) { e.printStackTrace(); } finally { try { if (br != null) br.close(); } catch (IOException ex) { ex.printStackTrace(); } } } } |
Java 7 Try With Resources Example
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
package com.journaldev.util; import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; public class Java7ResourceManagement { public static void main(String[] args) { try (BufferedReader br = new BufferedReader(new FileReader( "C:\journaldev.txt"))) { System.out.println(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } } |
Java try with resources benefits
Some of the benefits of using try with resources in java are;
- More readable code and easy to write.
- Automatic resource management.
- Number of lines of code is reduced.
- No need of finally block just to close the resources.
- We can open multiple resources in try-with-resources statement separated by a semicolon. For example, we can write following code:
123456789try (BufferedReader br = new BufferedReader(new FileReader("C:\journaldev.txt"));java.io.BufferedWriter writer = java.nio.file.Files.newBufferedWriter(FileSystems.getDefault().getPath("C:\journaldev.txt"), Charset.defaultCharset())) {System.out.println(br.readLine());} catch (IOException e) {e.printStackTrace();} - When multiple resources are opened in try-with-resources, it closes them in the reverse order to avoid any dependency issue. You can extend my resource program to prove that.
Java 7 has introduced a new interface java.lang.AutoCloseable
. To use any resource in try-with-resources, it must implement AutoCloseable
interface else java compiler will throw compilation error.
Lets confirm this with an example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
package com.journaldev.util; import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.nio.charset.Charset; import java.nio.file.FileSystems; public class Java7ResourceManagement { public static void main(String[] args) { try (MyResource mr = new MyResource()) { System.out.println("MyResource created in try-with-resources"); } catch (Exception e) { e.printStackTrace(); } System.out.println("Out of try-catch block."); } static class MyResource implements AutoCloseable{ @Override public void close() throws Exception { System.out.println("Closing MyResource"); } } } |
The output of the above program is:
1 2 3 4 5 |
<span style="color: #008000;"><strong><code> MyResource created in try-with-resources Closing MyResource Out of try-catch block. </code></strong></span> |
From the output, it’s clear that as soon as the try-catch block is finished, the resource close method is called.
Try with Resources Exceptions
There is one difference to note between try-catch-finally and try-with-resources in case of exceptions.
If an exception is thrown in both try block and finally block, the method returns the exception thrown in finally block.
For try-with-resources, if an exception is thrown in a try block and in a try-with-resources statement, then the method returns the exception thrown in the try block.
To better clarify this difference, we will see sample code.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 |
package com.journaldev.util; public class Java7ResourceManagement { public static void main(String[] args) throws Exception { try { tryWithResourceException(); } catch (Exception e) { System.out.println(e.getMessage()); } try { normalTryException(); } catch (Exception e) { System.out.println(e.getMessage()); } } private static void normalTryException() throws Exception { MyResource mr = null; try { mr = new MyResource(); System.out.println("MyResource created in the try block"); if (true) throw new Exception("Exception in try"); } finally { if (mr != null) mr.close(); } } private static void tryWithResourceException() throws Exception { try (MyResource mr = new MyResource()) { System.out.println("MyResource created in try-with-resources"); if (true) throw new Exception("Exception in try"); } } static class MyResource implements AutoCloseable { @Override public void close() throws Exception { System.out.println("Closing MyResource"); throw new Exception("Exception in Closing"); } } } |
The output of the above program is:
1 2 3 4 5 6 7 8 |
<span style="color: #008000;"><strong><code> MyResource created in try-with-resources Closing MyResource Exception in try MyResource created in the try block Closing MyResource Exception in Closing </code></strong></span> |
The output of the program proves the difference given above. That’s all for the Java 7 try-with-resources.