Saturday, May 11, 2013

try-with-resources

                 Try-with-resources is wonderful feature of Java 7.This feature introduced by Sun people as a part of Exception Handling.Try-with-resources means if we use any resources with-in the try block,the resources are closed automatically after completing usage of Try block.
                    
                    Generally try block is used when program has risky code,that risky code is kept inside of try block. Up-to Java 6 version,any clean up code is kept inside finally block.So that length of the code will be increased at a time performance will be decreased.For this reason Sun people introduced try-with-resources in java 7 version related to Exception Handling.
                      
                        The main advantage of try-with-resources is all resources with are open as part of try block will be closed automatically and we are not require to close explicitly.

Syntax of Try-with-resources:

   try(R1;R2;R3:...)
   {
      ---
      ---
    }
   
    Where R1,R2,and R3 are resources should be separated with semicolon and autoclosable resources.A resource is said to Autoclosable if and only if the corresponding class implements java.lang.AutoClosable interface either directly or indirectly.

Important Point related to Try-with-resources:
      
1. All resource reference variables are implicitly final. Hence with in the try block we cannot perform reassignment.

2. Until Java 6 version try is always associated with catch or finally.But from Java 7 onward's we can take try without catch or finally.

3. By using try-with-resources,finally block will become Dummy and we are not require to write finally block explicitly because the resources will be closed automatically.

Example Program With try-with-resources:

import java.io.BufferReader;
import java.io.FileReader;
import java.io.IOException;

class TryExample
{
   public static void main(String[] args) throws IOException
     {
       try(BufferReader br=new BufferReader(new FileReader("c:\\Data.txt")))
        {
           String line;
           
           while((line=br.readLine())!=null)
              {
                  System.out.println(line);
               }//while
          }//try
      }//end main()
 }// end class
             In the above program i write try block without catch or finally blocks,
Java 7 onward it is possible and resources will be automatically closed.














No comments:

Post a Comment