User defined Exception in Java | Custom Exception

In earlier tutorials, we have seen predefined exceptions provided by the Java platform. These predefined exceptions are used to handle errors occurring in the program.

But sometimes the programmer wants to create his own customized exception as per requirements of the application which is called user-defined exception or custom exception.

Custom exceptions in Java are those exceptions which are created by a programmer to meet their specific requirements of the application.

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

How to create your own User-defined Exception in Java?


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

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

class OwnException extends Exception

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

OwnException()
{

 }

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

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

Step 4: In the last step, we need to create an object of 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 custom exceptions better.


Program source code 1:

package customExceptionProgram;
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

Program source code 2:

public class OwnException extends Exception
{
// Declare parameterized constructor with String as a parameter. 
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 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

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 source code 3:

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

Final words
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 have to keep in mind.

Thanks for reading!!!