How to create a user defined exception (custom exception) in java?

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.

Example

 Live Demo

import java.util.Scanner;
public class ExceptionExample {
   public static void main(String args[]) {
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter first number: ");
      int a = sc.nextInt();
      System.out.println("Enter second number: ");
      int b = sc.nextInt();
      int c = a/b;
      System.out.println("The result is: "+c);
   }
}

Output

Enter first number:
100
Enter second number:
0
Exception in thread "main" java.lang.ArithmeticException: / by zero
at ExceptionExample.main(ExceptionExample.java:10)

User defined exceptions

You can create your own exceptions in Java.

  • 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.

To create a user defined exception extend one of the above mentioned classes. To display the message override the toString() method or, call the superclass parameterized constructor by passing the message in String format.

AgeDoesnotMatchException(String msg){
   super(msg);
}
Or,
public String toString(){
   return "CustomException[Age is not between 17 and 24]";
}

Then, in other classes wherever you need this exception to be raised, create an object of the created custom exception class and, throw the exception using the throw keyword.

MyException ex = new MyException ();
If(condition……….){
   throw ex;
}

Example

In the following Java program, we are creating a custom exception class with name AgeDoesnotMatchException.

public class AgeDoesnotMatchException extends Exception{
   (String msg){
      super(msg);
   }
}

Another class Student contains two private variables name, age and, a parameterized constructor which initializes the instance variables.

Form the main method we are accepting name and age values from user and initializing Student class by passing the accepted values.

In the constructor of the Student class we have created an object of the exception AgeDoesnotMatchException and raised the exception (using throws) if the age value is between 17 and 24.

public class Student extends RuntimeException {
   private String name;
   private int age;
   public Student(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();
      Student obj = new Student(name, age);
      obj.display();
   }
}

Output

On executing this program, you need to pass name and age values from keyboard. If the given age value id not between 17 and 24 then exception occurs as shown below −

Enter the name of the Student:
Krishna
Enter the age of the Student should be 17 to 24 (including 17 and 24):
14
AgeDoesnotMatchException: Age is not between 17 and 24
Name of the Student: Krishna'
Age of the Student: 14
at Student.<init>(Student.java:18)
at Student.main(Student.java:39)
raja
Published on 03-Jul-2019 13:42:12
Advertisements