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

An Exception is an abnormal condition that arises in a code sequence at run time. Exceptions are run time errors. Exceptions generated by the Java are related to the fundamental errors that violate the Java language constraints.

All exception classes are subtypes of the java.lang.Exception class. The exception class is a subclass of the Throwable class. Java defines several exception classes inside the standard package java.lang. Some examples of exceptions are ArithmeticException, ArrayIndexOutOfBoundsException, IndexOutOfBoundsException, NullPointerException, NumberFormatException, ClassNotFoundException,etc.When Java Interpreter caught an error such as divide by zero, the interpreter creates an exception object and throws it to inform that an error has occurred.

Java has its own exception handling mechanism. It performs the following task:
  1. Find the problem – Hit the exception
  2. Inform that an error has occurred – Throw the exception
  3. Receives the error information – Catch the exception
  4. Take corrective active – Handle the exception
In this program, we have created an exception class AgeException which extends the built-in Exception class. In main method, we read the input from user using Scanner after that we check the age in try block. If it is less than 18 then it will throw an exception other it will display message "Valid age".


PROGRAM
import java.util.Scanner;

class AgeException extends Exception {
 
 public AgeException(String str) {
  System.out.println(str);
 }
}
public class AgeExcDemo {

 public static void main(String[] args) {
  Scanner s = new Scanner(System.in);
  System.out.print("Enter ur age :: ");
  int age = s.nextInt();
  
  try {
   if(age < 18) 
    throw new AgeException("Invalid age");
   else
    System.out.println("Valid age");
  }
  catch (AgeException a) {
   System.out.println(a);
  }
 }
}
OUTPUT 1
C:\>javac AgeExcDemo.java
C:\>java AgeExcDemo
Enter ur age :: 15
Invalid age
exception.AgeException
OUTPUT 2
C:\>javac AgeExcDemo.java
C:\>java AgeExcDemo
Enter ur age :: 20
Valid age

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.