Friday, 5 September 2014

Exception Handling

//Program for Exception
class ExceptionDemo
{
    public static void main(String soham[])
    {
         int a = 10,b = 0,c;
         int arr[] = new int[2];

        try
        {
             arr[2] = 2;
        }
        catch(ArrayIndexOutOfBoundsException ae)
        {
            System.out.print("\nException: Array index out of bound");
        }

        finally
       {
           System.out.print("\nFinally statement execution is compulsary");
       }
   }
}
Output


//Program for Exception in Method
class ExceptionDemoMethod
{
    public static void main(String s[])
    {
         ExceptionDemoMethod edm = new ExceptionDemoMethod();

        try
        {
             edm.e_method();
        }
        catch(Exception e)
        {
            System.out.print("\nException: "+e);
        }
    }

    public void e_method() throws Exception
    {
        int a = 10,b = 0,c;
        c = a/b;
    }
}
Output


//Program for Custom Exception
import java.io.*;
class MyCustomException extends Exception
{
   private int age;

   public MyCustomException(int age)
   {
        this.age = age;
   }
  
   public String toString()
   {
        return "My Exception ["+age+"]";
   }
}

public class CustomExceptionDemo
{
   static void Test(int age) throws MyCustomException
   {
        int r = 0;
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        if(age <= 18)
        {
            System.out.print("\nYou are NOT eligible for voting!!!");
            throw new MyCustomException(age);
        }

        System.out.print("\n1.BJP \n2.CONGRESS \n3.MNS \n4.OTHERS");

        try
        {
            System.out.print("\nEnter your representative: ");
            r = Integer.parseInt(br.readLine());
        }
        catch (Exception e)
        {
            System.out.print("\n"+e);
        }

        System.out.println("\nYour VOTE has been casted. \nTHANK YOU");
   }

   public static void main(String soham[]) throws Exception
   {
        int age;
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

        System.out.print("\nEnter your age:");
        age = Integer.parseInt(br.readLine());

        try
        {
            Test(age);
        }
        catch (MyCustomException mce)
        {
            System.out.println("\n" +mce.toString());
        }
   }
}

No comments:

Post a Comment