User defined Exception in Java with Example

In this tutorial, we will understand what is a user defined exception or custom exception in Java with the help of examples.

As we have read about several predefined or built-in exceptions provided by the Java platform in the earlier tutorial. These predefined exceptions are used to handle certain errors occurring in the Java program.

Sometimes, predefined exceptions in Java are not suitable for describing a certain situation. In other words, the predefined exception classes of Java do not fit as per our needs in certain scenarios.

In such cases, the programmer wants to create his own customized exception as per requirements of the application, which is called user-defined exception or custom exception in Java.

User-defined exceptions in Java are those exceptions that are created by a programmer (or user) to meet the specific requirements of the application. That’s why it is also known as user-defined exception. It is useful when we want to properly handle the cases that are highly specific and unique to different applications. For example:

1. A banking application, a customer whose age is lower than 18 years, the program throws a custom exception indicating “needs to open a joint account”.

2. Voting age in India: If a person’s age entered is less than 18 years, the program throws “invalid age” as a custom exception.

Actually, there are mainly two drawbacks of predefined exception handling mechanism. They are:

  • Predefined exceptions of Java always generate the exception report in a predefined format.
  • After generating the exception report, it immediately terminates the execution of the program.

The user-defined exception handling mechanism does not contain the above explained two drawbacks. It can generate the report of error message in any special format that we prefer. It will automatically resume the execution of the program after generating the error report.

How to Create Your Own User-defined Exception in Java?


There are the following steps that are followed in creating a user-defined exception or custom exception in Java. They are as follows:

Step 1: User-defined exceptions can be created simply by extending the Exception class. This is done as:

class OwnException extends Exception

Here, we have defined our own exception class named OwnException as a subclass of an existing Java Exception class. Throwable class is the superclass for an entire family of exception classes, which is declared in java.lang.Throwable package.

Step 2: If you do not want to store any exception details, define a default constructor in your own exception class. We can do this as follows:

OwnException()
{

}

Step 3: If you want to store exception details, define a parameterized constructor with string as a parameter, call the superclass (Exception) constructor from this, and store variable “str”. This can be done as follows:

OwnException(String str)
{
  super(str); // Call superclass exception constructor and store variable "str" in it.
}

Step 4: In the last step, we need to create an object of the user-defined exception class and throw it using throw clause.

OwnException obj = new OwnException("Exception details");
  throw obj;
or,
 throw new OwnException("Exception details");

Let’s take a simple example program to understand the custom exception more clearly based on the above points.


Program code 1:

package customExceptionProgram;
// Define a custom exception class that extends Exception
public class OwnException extends Exception
{
// Declare default constructor.
   OwnException()
   {
  
   }
}
public class MyClass {
public static void main(String[] args)
{
   try
   { 
   // Create an object of user defined exception and throw it using throw clause.
      OwnException obj = new OwnException();
      throw obj; 
   } 
   catch (OwnException ex) 
   { 
      System.out.println("Caught a user defined exception"); 
   } 	
 }
}
Output:
       Caught a user defined exception

In this example, we have defined a user-defined class, named OwnException that extends the built-in Exception class. By extending Exception, OwnException becomes a checked exception, which means it must be either caught (handled) or declared to be thrown.

Then, we have defined a default constructor for the OwnException class. It doesn’t contain any code within its body. Inside the main method, we have used the try-catch block to handle the custom exception. To handle custom exceptions, we can use a combination of the try, catch, and finally blocks.


The try block contains the code that may throw an exception, the catch block catches and handles the exception. The finally block contains code that always executes, whether an exception occurs or not.

Inside the try block, we have created an instance of OwnException class (i.e. user-defined class) and thrown it using the throw clause. We use it when we want to throw an exception explicitly and want to handle it using a catch block. The statement throw obj; throws the OwnException object, indicating that an exceptional condition has occurred.

In the catch block, the code catches the OwnException object that was thrown by try block. Within the catch block, we have displayed a message indicating that a user-defined exception has been caught.

Program code 2:

package customExceptionProgram;
// Define a user-defined exception class that extends Exception
public class OwnException extends Exception
{
// Declare a parameterized constructor with a parameter str of type string. 
   OwnException(String str)
   {
     super(str); // Call super exception class constructor.
   }
}
public class MyClass {
public static void main(String[] args)
{
   try
   { 
   // Create an object of user defined exception and throw it using the throw clause.
      OwnException obj = new OwnException("Creating user defined exception");
      throw obj;

   // or, throw new OwnException("Creating user defined exception"); 
   } 
   catch (OwnException ex) 
   { 
      System.out.println("Caught a user defined exception"); 
      System.out.println(ex.getMessage());
   } 	
 }
}
Output:
      Caught a user defined exception
      Creating user defined exception

In this example, we have defined a parameterized constructor with a string parameter str. Inside the constructor, it calls the constructor of the superclass (Exception) using super(str). This will store the exception details for the exception.

Inside the main method, we have created an object of the OwnException class with a custom error message, “Creating user defined exception.”

In the catch block, the code catches and handles the OwnException that was thrown by try block. Inside the catch block, we have used getMessage() method to display the error message associated with the caught exception in the program.


Let’s take an example program where we will evaluate candidate’s age to vote. If the candidate’s age is less than 18 years, the program will throw a custom exception “Invalid age”. See the program source code to understand better and follow all steps.

Program code 3:

package customExceptionProgram;
public class InvalidAgeException extends Exception
{
// Declare a parameterized exception with string str as a parameter.
   InvalidAgeException(String str)
   {
      super(str);
   }
}
import java.util.Scanner;
public class TestClass 
{
   private static int age;
   static void validate() throws InvalidAgeException
   { 
   // Creating an object of Scanner class.
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter your age");
      age = sc.nextInt();

      if(age < 18)  
          throw new InvalidAgeException("Invalid Age, You are not eligible to vote");  
      else  
          System.out.println("Welcome to vote");  
    }  
public static void main(String[] args)
{
   try
   {  
      validate();  
   }
   catch(Exception e)
   {
      System.out.println("Caught an Exception: \n "+e);
   }   
 }  
}
Output:
First Execution:
      Enter your age
      7
      Caught an Exception: 
      customExceptionProgram.InvalidAgeException: Invalid Age, You are not eligible to vote

Second Execution:
      Enter your age
      40
      Welcome to vote

In this example program, we are throwing our own exception when candidate’s age to vote is less than eighteen years. Here, we are throwing our own exception using throw statement. In addition to it, we have created an instance of the Scanner class named sc.

The Scanner class is a part of Java’s standard library that we use to read input from various sources, including the keyboard (in this case, denoted as System.in). It allows the program to interact with the user by accepting input from the console. The statement age = sc.nextInt(); reads an integer input entered by the user from the console and assigns it to a variable named age.


Let’s take an example in which we will take a number from the user and find out the square of it. If the user enters a number greater than 100, we will print a message.

Program code 5:

package customExceptionProgram;
// Define a custom exception class that extends Exception
class MyException extends Exception {
 
// Create a constructor for the exception class
   public MyException(String str) {
     super(str);
 }
} 
import java.util.Scanner;
public class SquareCalculator {
public static void main(String[] args) 
{
 // Create an object of Scanner class to read the input.
    Scanner sc = new Scanner(System.in);

    try {
       System.out.print("Enter a number less than 100: ");
       int number = sc.nextInt();
       int square = number * number;
       if (number >= 100)
       {
    	// If the number is greater than 100, throw the custom exception
           throw new MyException("Please enter a number less than 100");
       } else {
           System.out.println("Square of " + number + " is " + square);
         }
     } catch (MyException e) {
         // Catch and handle the custom exception
            System.out.println("Custom Exception Caught: " + e.getMessage());
     } catch (Exception e) {
         // Handle other exceptions, e.g., if the user enters non-numeric input
            System.out.println("An error occurred: " + e.getMessage());
     } finally {
            sc.close();
       }
   }
}
Output:
       Enter a number less than 100: 25
       Square of 25 is 625
       Enter a number less than 100: 105
       Custom Exception Caught: Please enter a number less than 100

Java allows the user to create its own user-defined exception or custom exception simply by declaring a subclass of exception class and using throw keyword. Only four steps in creating user-defined exception in Java that you should keep in mind. Hope that you will have understood the basic concept of creating custom exception and practiced all example programs. In the next, we will understand chained exception in Java with the help of examples.
Thanks for reading!!!

⇐ Prev Next ⇒

Please share your love