Showing posts with label User defined exception. Show all posts
Showing posts with label User defined exception. Show all posts

Saturday, 17 September 2011

User defined exception

class AgeException extends Exception
{
    private String message;
   
    public AgeException()
    {
        this.message = "Age Cannot Be Less Than 1";
    }
   
    public AgeException(String message)
    {
        this.message = message;
    }
   
    public String toString()
    {
        return this.message;
    }
}

class SetAge
{
    private int age;
   
    public void setAge(int age)
    {
        this.age = age;
    }
   
   
    public void showAge()
    {
        String message = "Age Cannot Be Greater Than 120";
       
        if(age >=1 && age <= 120)
        {
            System.out.println("Age Set : " + age);
        }
   
        else if ( age > 120)
        {
            throw new AgeException(message);
           
        }
        else
        {
            throw new AgeException();
        }
    }
}



public class AgeMain
{
    public static void main(String[] args)
    {
        SetAge setage = null;
       
        try
        {
            setage = new SetAge();
            setage.setAge(-5);
           
            setage.showAge();
           
        }
        catch(NullPointerException exception)
        {
            System.out.println("Exception Object Reference is Null ");
        }

        catch(AgeException exception )
        {
            System.out.println("Exceptio  : " +  exception);
        }
    }
}

IllegalArgumentException exeption


public class SetValues
{
    public static void main(String[] args)
    {
        try
        {
            System.out.println("Value : " + Integer.parseInt("4545"));
            System.out.println("Value : " + Integer.parseInt("60,40"));
        }
        catch(IllegalArgumentException exeption)
        {
            System.out.println("Exception : " + exeption);
        }
    }
}

IndexOutOfBoundsException exception in java


public class ArrayTesting
{
    public static void main(String[] args)
    {
        int arr[]= new int[2];
       
        arr[0]=1;
        arr[1]=2;
       
       
        int res;
       
       
        try
        {
            res = arr[0] + arr[1] + arr[2];
            System.out.println("Sum is : " + res);
        }
        catch(IndexOutOfBoundsException exception)
        {
            System.err.println("Exception : " +exception);
        }
       
       
    }
}