You are here: Home / Topics / User defined exception example in Java

User defined exception example in Java

Filed under: Java on 2023-09-19 06:49:36

// Program to create User-defined Exception
// for checking validity of age.

class InvalidAgeException extends Exception 
{
private int age;

InvalidAgeException(int a) 
{
 age = a;
}

public String toString() 
{
 return "Age: " + age + " is not a valid age.";
}
}

class  Exception14 
{
static void checkAge(int age) throws InvalidAgeException
{
 System.out.println("Checking Age Validity : (" + age + ")");
 if(age < 0 || age > 100)
  throw new InvalidAgeException(age);
 System.out.println("Age: " + age + " is a valid age.");
}

public static void main(String args[ ]) 
{
 try 
 {
  checkAge(25);
  checkAge(-5);
 } 
 catch (InvalidAgeException e) 
 {
  System.out.println("Caught: " + e);
 }
}
}


Output:

Checking Age Validity : (25)
Age: 25 is a valid age.
Checking Age Validity : (-5)
Caught: Age: -5 is not a valid age.

About Author:
M
Mr. Dubey     View Profile
Founder and CEO of MCQ Buddy. I just like to help others. This portal helps students in getting study material free.