What is try-with-resources in java?

The try-with-resources statement introduced in Java 7, a nice feature on exception handling. It is a try statement that declares one or more resources. It was introduced because of some resources used in Java (like SQL connections or streams) being difficult to be handled properly.

Old School Style - try...catch...finally

import java.util.*; import java.io.*; public class TestClass{ public static void main(String[] args) { try { FileReader fileReader = new FileReader("D:\\test.txt"); int chr = fileReader.read(); while(chr != -1) { System.out.print((char) chr); chr = fileReader.read(); } if(fileReader != null) { fileReader.close(); } } catch (IOException e){ e.printStackTrace(); } finally{ //code here } } }

Replacing try–catch-finally with try-with-resources

The new try-with-resources functionality is to replace the traditional and verbose try-catch-finally block. Resource instantiation should be done within try(). A parenthesis () is introduced after try statement and the resource instantiation should happen within that parenthesis as below:
import java.util.*; import java.io.*; public class TestClass{ public static void main(String[] args) { try (FileReader fileReader = new FileReader("D:\\test.txt");){ int chr = fileReader.read(); while(chr != -1) { System.out.print((char) chr); chr = fileReader.read(); } } catch (IOException e){ e.printStackTrace(); } } }
The resources are automatically closed after the try. In the try resources list, you can declare several resources, but all these resources must implement the java.lang.AutoCloseable interface.