Java try with resources

Posted in Exception Handling By Raj On December 28, 2017


In my previous article, I have explained how to use try-catch-final in java,  in this article I am going to cover  try-with -resources which is an automatic resource management in Java Exception handling

The try-with-resources is introduced in Java 1.7. the main advantage of this you do not need to explicitly close resources in the finally block, the try-with-resource will help us to automatically close’s resources once all statements within the try block executed successfully 

You can use try-with-resources only for classes that implement java.lang.AutoCloseable interface

Example: try-catch block

Example: try-with-resource

In the below example, the object for FileInputStream is created inside the parenthesis. once the code execution is completed it will automatically close, because the FileInputStream implements an AutoCloseable interface

I am intentionally throwing exception here if you go and see the logs you will not see the exception which is in the catch block instead of that you will see the exception which is in the try block because, in the try-with-resource, if any error occurs it will not throw to catch block instead of that it will throw into try block itself