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

Comments

Popular posts from this blog

Program to define a class 'employee' with data members as empid, name and salary. Accept data for 5 objects using Array of objects and print it.

Program to input age from user and throw user-defined exception if entered age is negative

Define a class Student with four data members such as name, roll no.,sub1, and sub2. Define appropriate methods to initialize and display the values of data members. Also calculate total marks and percentage scored by student.