What is try-with-resources in java?

The try-with-resources statement, introduced in Java 7, is a valuable addition to exception handling. This construct serves as a try statement that declares and manages one or more resources, particularly addressing the challenge of correctly handling resources like SQL connections or streams, which can be cumbersome to manage manually. By incorporating the try-with-resources statement, Java provides an elegant and efficient solution to handle resources, enhancing code readability and maintainability.

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(); } } }

Resources are automatically closed after the try block execution, ensuring proper resource management. The try-with-resources syntax allows for the declaration of multiple resources in the try-with-resources list, but it is crucial that all these resources implement the java.lang.AutoCloseable interface. By implementing AutoCloseable, resources can define their own close() method, which will be automatically invoked by the try-with-resources statement when the try block completes or if any exceptions are thrown, ensuring that resources are released properly without the need for explicit resource cleanup.

Conclusion

Try-with-resources in Java is a feature introduced to automate resource management, allowing for automatic closure of resources after the try block. Resources declared in the try-with-resources list must implement the java.lang.AutoCloseable interface, ensuring proper cleanup without the need for explicit resource handling, resulting in more concise and robust exception handling in Java.