Wednesday, 1 February 2017

TRY WITH RESOURCE IN JAVA

Try with resources is the concept which works in java 1.7 onwards. As we have already discussed that to close any resource we do it inside finally block. But the finally block can be done in java 1.6 also. So now we think what is the new thing while working with try with resource. Let us take an example –

Example –
import java.util.Scanner;
public class Exception1 {
          public static void main(String[] args){                 
                   try(Scanner sc = new Scanner(System.in))
                   {
                             System.out.println("Enter your elligible age");
                             int age = sc.nextInt();
                             if(age<18)
                                      System.out.println("Not elligible");
                             else
                                      System.out.println("You are elligible for voting");
                   }                                    
          }
}

Output –
Enter your elligible age
17
Not elligible

Note – In the above example we have seen that we have declared Scanner resource inside try as a parameter which means we are allocating a resource as well as if any error occurred inside try block the resource will be deallocated. We don’t need to write separate finally block for it. Even here we are not writing catch block for the try block also.

No comments:

Post a Comment