When and why to use try-with-resource syntax in java? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

When and why to use try-with-resource syntax in java?

I thought i knew every thing about exception handling in java untill i heard about try-with-resource syntax. However i am unable to understand why and when to use it Heres an example: try( FileOutputStream fos = new FileOutputStream("file.txt") ){ fos.write( "hello".getBytes() ); } catch(Exception e){ } Cant we simply write every thing inside the body of try block try{ FileOutputStream fos = new FileOutputStream("file.txt"); fos.write( "hello".getBytes() ); }catch(Exception e){}

20th Apr 2020, 12:52 PM
Razbry
Razbry - avatar
2 Answers
+ 3
You can. But first one advantage is that after try block completed, the resouse opened by try parameter will get closed automatically.. So which is same as try{ FileOutputStream fos = new FileOutputStream("file.txt"); fos.write( "hello".getBytes() ); } catch(Exception e) {} finally { fos.close(); } When : when resource object is implemented from AutoCloseable() interface, it better to go with this short hand type. And in, If any chance of finally may raise exception, and above example have chance. Why : short hand, & automatically handles closing of resource to prevent lose of data..
20th Apr 2020, 1:13 PM
Jayakrishna 🇮🇳
+ 1
Hello Razbry For more information you can read this: https://www.baeldung.com/java-try-with-resources
20th Apr 2020, 1:26 PM
Denise Roßberg
Denise Roßberg - avatar