Tuesday, 29 November 2016

Program to input name and age of a person and throw an user-defined exception, if the entered age is negative

The given program contains an exception class AgeNegativeException which throws an negative age exception. We have to read name and age from user at run time and throw an exception if the entered age is negative. Here we have used the Scanner class and its methods like nextLine( ), nextInt( ) to read string and number respectively. The getMessage( ) method of Throwable class is used to return a description of the exception.

PROGRAM
import java.util.Scanner;

class AgeNegativeException extends Exception {
 
 public AgeNegativeException(String msg) {
  
  super(msg);
 }
}

public class NameAgeExcDemo {

 public static void main(String[] args) {

  Scanner s = new Scanner(System.in);
  System.out.print("Enter ur name :: ");
  String name = s.nextLine();
  System.out.print("Enter ur age :: ");
  int age = s.nextInt();
  
  try {
   if(age < 0)
    throw new AgeNegativeException("Age must be greater than 0");
   else
    System.out.println("Valid age !!!");
  }
  catch (AgeNegativeException a) {
   System.out.println("Caught an exception");
   System.out.println(a.getMessage());
  }
 }

}
OUTPUT 1
C:\>javac NameAgeExcDemo.java
C:\>java NameAgeExcDemo
Enter ur name :: Sachin
Enter ur age :: 19
Valid age !!!
OUTPUT 2
C:\>javac NameAgeExcDemo.java
C:\>java NameAgeExcDemo
Enter ur name :: Rohan
Enter ur age :: -12
Caught an exception
Age must be greater than 0

No comments:

Post a Comment