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

Java 8Object Oriented ProgrammingProgramming

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.


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){
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) {
      } = name;
      this.age = age;
   public void display(){
      System.out.println("Name of the Student: " );
      System.out.println("Age of the Student: "+this.age );
   public static void main(String args[]) {
      Scanner sc= new Scanner(;
      System.out.println("Enter the name of the Student: ");
      String name =;
      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);


Enter the name of the Student:
Enter the age of the Student, should be 17 to 24 (including 17 and 24):
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>(
at july_set3.CustomException.main(
Updated on 02-Jul-2020 14:38:56