Write a program to handle negative age exception

Write a program to handle negative age exception

1.Exception Creation Program
package studentage;
public class Nage extends Exception
{
    public Nage(String s)
    {
        super(s);
    }
};

2.Exception verification Program
package verifyage;
import studentage.Nage;
public class Verify
{
    public void checkage(int a) throws Nage
    {
        if(a>0)
        { 
            System.out.print("valid age");
        }
        else
        {
            Nage n=new Nage("Invalid age");
            throw(n);
        }
    }
}

3.Main Program
import studentage.Nage;
import verifyage.Verify;
import java.util.Scanner;
public class Main
{
    public static void main(String args[])
    {
        System.out.print("Enter your age : ");
        Scanner s=new Scanner(System.in);
        try
        {
            int age=s.nextInt();
            Verify v=new Verify();
            v.checkage(age);
            System.out.print("your age is : "+age);
        }
        catch(Nage ne)
        {
            System.out.println("Age should not be Nagetive");
        }
    }
}


Output:

Enter your age: 20
Valid age
your age is : 20

Enter your age : -20
Age should not be negative.


What is difference between the throws and throw ?
Throws is a keyword used to forward the exception to the method call whereas throw is a keyword used to throw exception to the method sign.
Throws always should be followed by method signature whereas throw keyword always should exist within method only.


Exception Handling In Java



More Questions


170 . Write a program to handle negative age exception
171 . Write a program to handle negative salary exception
172 . Write a Simple interest program to handle negative amount and duration and interest using user defined exception
173 . Write a String length program
174 . Write a string charAt() method program
175 . Write a string toLowerCase() Program
176 . Write a String toUpperCase() program
177 . Write a string concat() program
178 . Write a string compareTo program
179 . Write a string compareToIgnoreCase() Program
180 . Write a string equals program