16.06. Try with resources

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 that needs to be closed else we will get a warning.

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

Contributed by: Poonam Tomar

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments