Showing posts with label Try-with-Resources. Show all posts
Showing posts with label Try-with-Resources. Show all posts

Try-with-Resources in Java 7

The try-with-resources statement is a try statement that declares one or more resources within try statement. A resource(s) is an object that must be closed after the program is finished with it. The try-with-resources statement ensures that each resource is closed at the end of the statement and finally block is no more required when we use it.
Try-with-Resources in Java 7


If we see earlier to Java 7 like which we are familiar with try-catch-finally block. Here if exception thrown from try block, then finally block will be executed. Suppose if finally block also thrown with exception then try block would probably be more relevant to propagate exception than finally block.

Lets see simple example with both try-catch-finally and try-with-resources.

try-catch-finally example to open a file and to read line by line.


public class TryCatchFinallyTest {
 
 public static void main(String[] args) {
  
  FileInputStream fis = null;
  BufferedReader br = null;
  
  try{
   fis = new FileInputStream("C:\\textfile.txt");
   br = new BufferedReader(new InputStreamReader(fis));
   
   String line = null;
   while ((line = br.readLine()) != null) {
    System.out.println(line);
   }
   
  }catch(IOException ex){
   ex.printStackTrace();
  }finally{
   if(fis != null){
    try {
     fis.close();
    } catch (IOException e) {
     e.printStackTrace();
    }   
   }
   if(br != null){
    try {
     br.close();
    } catch (IOException e) {
     e.printStackTrace();
    }
   }
  }   
 } 
}


try-with-resources example to open a file and to read line by line.

public class TryWithResourceTest {
 
 public static void main(String[] args) {
  
  try(FileInputStream fis = new FileInputStream("C:\\textfile.txt");
    BufferedReader br = new BufferedReader(new InputStreamReader(fis))
    ){
   
   String line = null;
   while ((line = br.readLine()) != null) {
    System.out.println(line);
   }   
  }  
 } 
}

If we see both examples we can find the difference in code. In Java 7 we have more simple and less code compared to earlier try-catch-finally block. Moreover from advantage side opened resources will be closed automatically once they are out of block, but in earlier we need to close explicitly.