+ 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){}
2 Antworten
+ 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..
+ 1
Hello Razbry
For more information you can read this: https://www.baeldung.com/java-try-with-resources