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.

import java.util.Scanner;

class AgeNegativeException extends Exception {
 public AgeNegativeException(String msg) {

public class NameAgeExcDemo {

 public static void main(String[] args) {

  Scanner s = new Scanner(;
  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");
    System.out.println("Valid age !!!");
  catch (AgeNegativeException a) {
   System.out.println("Caught an exception");

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


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.

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.

Program to draw Smiley in Applet