Friday, 26 May 2017

Java try with resource statement ~ GNIITHELP

JDK 7 introduces a new version of try statement known as try-with-resources statement. This feature add another way to exception handling with resources management,it is also referred to as automatic resource management.
Syntax
try(resource-specification)
{
//use the resource
}catch()
{...}
This try statement contains a paranthesis in which one or more resources is declare. Any object that implements java.lang.AutoCloseable or java.io.Closeable, can be passed as a parameter to try statement. A resource is an object that is used in program and must be closed after the program is finished. The try-with-resources statement ensures that each resource is closed at the end of the statement, you do not have to explicitly close the resources.


Example without using try with Resource Statement

import java.io.*;
class Test
{
public static void main(String[] args)
{
try{
String str;
//opening file in read mode using BufferedReader stream
BufferedReader br=new BufferedReader(new FileReader("d:\\myfile.txt"));   
while((str=br.readLine())!=null)
 {
System.out.println(str);
 }      
br.close(); //closing BufferedReader stream
}catch(IOException ie)
{  System.out.println("exception");  }
 }
}

Example using try with Resource Statement

import java.io.*;
class Test
{
public static void main(String[] args)
{
try(BufferedReader br=new BufferedReader(new FileReader("d:\\myfile.txt")))
{
String str;
while((str=br.readLine())!=null)
{
System.out.println(str);
}
}catch(IOException ie)
{  System.out.println("exception");  }
}
}
NOTE: In the above example, we do not need to explicitly call close() method to close BufferedReader stream.

No comments:

Post a Comment