Wednesday, 1 February 2017

THROW AND THROWS IN JAVA

Throws – Suppose let us take an example, if in our code there is some kind of exception and we don’t want to handle those exceptions then, with the help of throws keyword we can suppress the exception. But as a good programmer we should always go for try and catch instead of throws. Throws should always be written just after the right side of the method. Checked exception should only be declared with throws.

Example –
import java.io.FileReader;
import java.io.IOException;
public class Exception1 {
          public static void main(String[] args) throws IOException{
                   FileReader fr = new FileReader("abc.txt");
                   int i;
                   while((i=fr.read())!=-1)
                   {
                             System.out.println((char)i);
                   }
                   System.out.println("Hello");
          }
}


Throw – We can either throw checked or unchecked exceptions. Throw keyword is basically used to throw custom exceptions. This is used to forcefully call the requested catch block.

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

Output –
Enter your elligible age
17
You are not elligible

No comments:

Post a Comment