Is it possible to create a custom exception in java without extending Exception class?


An exception is an issue (run time error) occurred during the execution of a program. When an exception occurred the program gets terminated abruptly and, the code past the line that generated the exception never gets executed.

User defined exceptions

You can create your own exceptions in Java and they are known as user defined exceptions or custom exceptions.

  • All exceptions must be a child of Throwable.
  • If you want to write a checked exception that is automatically enforced by the Handle or Declare Rule, you need to extend the Exception class.
  • If you want to write a runtime exception, you need to extend the RuntimeException class.

Is it mandatory to extend Exception class

No, it is nor mandatory to extend the exception class to create custom exceptions, you can create them just by extending Throwable class, the super class of all exceptions.

Example

The following Java example creates a custom exception named AgeDoesnotMatchException , which restricts age of the user between 17 and 24. Here we are creating it without extending the Exception class.

import java.util.Scanner;
class AgeDoesnotMatchException extends Throwable{
   AgeDoesnotMatchException(String msg){
      super(msg);
   }
}
public class CustomException{
   private String name;
   private int age;
   public CustomException(String name, int age){
      try {
         if (age<17||age>24) {
            String msg = "Age is not between 17 and 24";
            AgeDoesnotMatchException ex = new AgeDoesnotMatchException(msg);
            throw ex;
         }
      }catch(AgeDoesnotMatchException e) {
         e.printStackTrace();
      }
      this.name = name;
      this.age = age;
   }
   public void display(){
      System.out.println("Name of the Student: "+this.name );
      System.out.println("Age of the Student: "+this.age );
   }
   public static void main(String args[]) {
      Scanner sc= new Scanner(System.in);
      System.out.println("Enter the name of the Student: ");
      String name = sc.next();
      System.out.println("Enter the age of the Student, should be 17 to 24 (including 17 and 24): ");
      int age = sc.nextInt();
      CustomException obj = new CustomException(name, age);
      obj.display();
   }
}

Output

Enter the name of the Student:
Krishna
Enter the age of the Student, should be 17 to 24 (including 17 and 24):
30
july_set3.AgeDoesnotMatchException: Age is not between 17 and 24
Name of the Student: Krishna
Age of the Student: 30
at july_set3.CustomException.<init>(CustomException.java:17)
at july_set3.CustomException.main(CustomException.java:36)
raja
Published on 06-Aug-2019 14:57:28
Advertisements