English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Can you create a custom exception in Java without extending the Exception class?

An exception is a problem that occurs during program execution (runtime error). When an exception occurs, the program will terminate abruptly, and the code after the line where the exception occurred will never be executed.

Exception defined by the user

You can use Java to create your own exceptions, which are called user-defined exceptions or custom exceptions.

  • All exceptions must be subclasses of Throwable.

  • If you want to write a checked exception that is automatically executed by Handle or Delare Rule, you need to extendExceptionclass.

  • If you want to write a runtime exception, you need to extendRuntimeExceptionclass.

Is it necessary to extend the Exception class

It is not mandatory to extend the Exception class to create custom exceptions. You can create them by extending the Throwable class (the superclass of all exceptions).

Example

The following Java example creates a custom exception named AgeDoesnotMatchException that restricts the user's age to17to24Between ages. Here, we create 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 Result

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)