Java Try with Resources


Today we will investigate Java Try with Resources. One of the Java 7 highlight is try-with-resources proclamation for programmed asset the executives.

Try with Resources

A asset is an article that must be shut once your program is finished utilizing it. For instance, a File asset or JDB asset for a database association or a >Socket< association asset. Prior to Java 7, there was no auto asset the board and we should expressly close the asset once our work is finished with it. For the most part, it was done in the finally square of a try-catch explanation. This methodology used to cause memory holes and execution hit when we neglected to close the resource.

Let's see a pseudo code scrap to comprehend this java attempt with assets feature.

Before Java 7:

 

try{ 

//open assets like File, Database association, Sockets etc 

} catch (FileNotFoundException e) { 

//Exception taking care of like FileNotFoundException, IOException etc 

}finally{ 

//close resources 

} 

Java 7 attempt with assets implementation:


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


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

Copy
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(); } } }
  1. More discernible code and simple to write.
  2. Automatic asset management.
  3. Number of lines of code is reduced.
  4. No need of at last square just to close the resources.
  5. We can open various assets in attempt with-assets articulation isolated by a semicolon. For instance, we can compose following code:
    Copy
    try (BufferedReader br = new BufferedReader(new FileReader( "C:\\journaldev.txt")); java.io.BufferedWriter author = java.nio.file.Files.newBufferedWriter(FileSystems.getDefault().getPath("C:\\journaldev.txt"), Charset.defaultCharset())) { System.out.println(br.readLine()); } catch (IOException e) { e.printStackTrace(); }
  6. When numerous assets are opened in attempt with-assets, it closes them in the switch request to maintain a strategic distance from any reliance issue. You can stretch out my asset program to demonstrate that.

Java 7 has presented another interface java.lang.AutoCloseable. To utilize any asset in attempt with-assets, it must execute AutoCloseable interface else java compiler will toss accumulation error.

Lets affirm this with an example:

Copy
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:

Copy
MyResource created in try-with-resources Closing MyResource Out of try-catch block.

From the yield, plainly when the attempt get square is done, the asset close strategy is called.

Try with Resources Exceptions

There is one contrast to note between attempt get at last and attempt with-assets if there should arise an occurrence of special cases.

If a special case is tossed in both attempt square lastly hinder, the strategy restores the exemption tossed in at long last block.

For attempt with-assets, if an exemption is tossed in an attempt square and in an attempt with-assets proclamation, at that point the technique restores the special case tossed in the attempt block.

To better clear up this distinction, we will see test code.

Copy
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:

Copy
MyResource created in try-with-resources Closing MyResource Exception in try MyResource created in the try block Closing MyResource Exception in Closing





© Journaldev Python 3 tutorial spring tutorial