Friday, March 25, 2016

Try with resources

Try-With-Resources

Before Java 7, finally blocks were put to close any resource allocations inside try block.

ex: 
   public void readFile(){

     FileInputStream input=null;
    try{
             input = new FileInputStream ("C:/myfile.txt");
             int data =input.read();
         }catch(Exception e){
          }finally{
              if(input!=null){
                         input.close();
                               }
}
}

In Java 7 we dont need to explicitly close the inputstream, if use the try with resources.
     ex:
          try(FileInputStream inputFile=new FileInputStream("C/myFile.txt")){

     }catch(Exception e){
    
     }

try can have multiple statements in the parenthes, provided each statement creates an object which implements java.lang.AutoClosable interface.

in pre java 7 try-catch-finally model, if an exception occurs in try and another in finally, the exception thrown in finally used to propagate. This don't give us a clear idea of what was the 
exception occured in the try catch.

In Try with resource, it is resolved. If exception occurs in try and during closing the resources,
the exception thrown in try block will propagate.

Custom Autoclosable implementations
   
Autclosable interface has only one method , public void close().

class MyResourceHandler implements AutoCloseable{

@Override
public void close() throws Exception {
System.out.println("closing the resources");

}


}


       

No comments:

Post a Comment