Try with resources

  • Eclipse: Oxygen
  • Java: 1.8

The try with resources is a command that whenever we allocate some resources, for example, Assigning a resource to take input from the Scanner class. If the user fails to close the resource, then it leads to a resource leak which could prove dangerous to the execution of a program. Hence after implementing the same in a try block, we can avoid the resource leak.

Whenever we are making use of data resources stream for example scanner class or Buffered class it needs to be closed after the program is finished with it. So, in the following program, the closing of resources is done by itself, try.

Inside this parenthesis, we are creating an object. This object is a resource which needs to be closed else we will get the warning.

try(BufferedWriter bw = new BufferedWriter(new FileWriter(file,true))

Contributed by: Poonam Tomar


Full stack Java Developer

   Buy me a coffee!

 

PayTM QR (INDIA)

Download file

Leave a Reply

avatar
  Subscribe  
Notify of
Close Menu