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
// TODO Auto-generated catch block
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
Log.error("Error occured while reading excel file");
Log.error("Error occured while reading excel file"+e.getMessage());
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
No related posts.
A technology enthusiast and a professional blogger from India. Through out my IT career, I have had the pleasure of working on various new technologies and built products like www.ziprides.com and some other products. Unfortunately, my attempts have not given me the desired results and as a result, I have finally decided to build a professional blog where I would like to share all my learnings and hoping to learn from other enthusiasts around the world.