Saturday 19 October 2013

Program to throw exception for a person whose age is below 18

//Program to throw exception for a person whose age is below 18
//Developed by Ahlam Ansari
import java.lang.Exception;
import java.util.*;
class OwnException extends Exception
{
    OwnException(String msg) throws OwnException
    {
          System.out.println("ALERT:  "+msg.toUpperCase());
    }
}

class MyOwnException
{
    public static void main(String ahlam[])
    {
        int n;
        Scanner d=new Scanner(System.in);
        System.out.println("Enter your age:");
        n=d.nextInt();
        try
        {
                if (n < 18)
              {
                    throw new OwnException("Your age is : " + n+" \nYou cannot vote");
              }
            else
            {
                System.out.println("Your age is : " + n+" \nYou are an adult and you can vote");
            }
        }
        catch(OwnException ex)
        {
            System.out.println("Caught: "+ex);
        }
    }
}

/*
Output:
C:\Users\Ahlam\Google Drive\My Lectures\Fall\OOPM\Programs>javac MyOwnException.
java

C:\Users\Ahlam\Google Drive\My Lectures\Fall\OOPM\Programs>java MyOwnException
Enter your age:
12
ALERT:  YOUR AGE IS : 12
YOU CANNOT VOTE
Caught: OwnException

C:\Users\Ahlam\Google Drive\My Lectures\Fall\OOPM\Programs>java MyOwnException
Enter your age:
22
Your age is : 22
You are an adult and you can vote

C:\Users\Ahlam\Google Drive\My Lectures\Fall\OOPM\Programs>
*/

No comments:

Post a Comment