Custom Exception in Java

Custom Exception in Java with Examples

In this article, I am going to discuss How to create User-Defined Exception or How to create a Custom Exception in Java with Examples. Please read our previous article where we discussed throw and throws keywords in Java. At the end of this article, you will understand the following pointers in detail.

  1. Types of Exceptions in Java
  2. Built-in exceptions in java
  3. User-defined or Custom Exception in Java
  4. How to Create Custom exception class in Java application?
  5. Why did you extend custom exception class from java.lang.Exception class?
  6. One Real-Time Example of User Defined Exception in Java Application
Types of Exceptions in Java:

There are two types of exception available in java

  1. Built-in Exceptions
  2. User-Defined or Custom Exceptions
Built-in exceptions in java:

Built-in exceptions are the exceptions that are all ready available in java. These exceptions are suitable to explain certain error situations. Some built-in exceptions are given below.

Built-in exceptions in java

User-defined or Custom Exception in Java:

The new exception class developed by a developer is called as the custom exception or user-defined exception. These classes must be a subclass of either Throwable or any one of its subclasses.

Most of the cases in projects custom exceptions classes are derived from Exception class. All exception classes defined by SUN are based on the java language and API requirement. So according to the business requirement developer must write their own exception class

How to Create a User-Defined or Custom Exception class in Java Application?

It is a two-step process

  1. Define a packaged public class deriving from java.lang.Exception
  2. Define public no-arg and String parameter constructor with super() call.

Note: No-arg constructor for creating exception objects without a message and parameterized constructor for creating an exception object with a message

Why did you extend custom exception class from java.lang.Exception class?

We created custom exception classes for throwing these exceptions when a condition is failed and that exception handling wants to be validated by the compiler so they must be extended from java.lang.Exception.

We must extend them from java.lang.RuntimeException class if we don’t want to validate these exception handling by the compiler. Since we don’t write exception classes for handling errors in JVM internal logic we don’t derive them from java.lang.Error

Also, we don’t derive them from java.lang.Throwable as it created a new category of exception and it is not recommended to create a new category of exceptions because this custom exception is not caught by the catch (Exception e). In projects, developers write catch(Exception e) to catch all types of exceptions and in this case, our exception is not caught

Sample Program for User-Defined Exception in Java
class MinBalanceException extends Exception
{
  public MinBalanceException ()
  {
    System.out.println ("Balance is low");
  }
}
public class Main
{
  public static void main (String[]args)
  {
    try
    {

      int acc[] = { 100, 101, 102, 103, 104, 105 };	// input can be got from runtime too 
      double balance[] = { 900, 2000, 1500, 1560, 1765.50 };
      System.out.println ("Account No\t" + "Balance\t");
      for (int i = 0; i < 5; i++)
   {
     System.out.println (acc[i] + "\t\t" + balance[i] + "\t");
     if (balance[i] < 1000)
     {
         throw new MinBalanceException ();	//throwing user defined exception
     }
   }
    }
    catch (MinBalanceException e)
    {
      System.out.println ("Exception caught");
    }
  }
}

Output:

Program for User Defined Exception in Java

One Real-Time Example of Custom or User-Defined Exception in Java Application:

Define custom exceptions InvalidAmountException, InsufficientFundsException to handle wrong operations done by customers in deposit, and withdraw operations.

TestCases:

  1. Throw InvalidAmountException if the user enters zero or –ve amount in deposit and withdraw operations.
  2. Throw InsufficientFundsException if the user enters the amount greater than the balance in case of withdrawing operations.
InvalidAmountException.java
package com.pkr.exceptions;
public class InvalidAmountException extends Exception
{
 public InvalidAmountException()
 {
  super();
 }
 public InvalidAmountException(String msg)
 {
  super(msg);
 }
}
InsufficientFundsException.java
package com.pkr.exceptions;
public class InsufficientFundsException extends Exception 
{
 public InsufficientFundsException()
 {
  super();
 }
 public InsufficientFundsException(String msg)
 {
  super(msg);
 }
}
Bank.java
package com.pkr.blogic;
import com.pkr.exceptions.*;
public interface Bank 
{
 public void deposite(double amount) throws InvalidAmountException;
 public double withdraw(double amount) throws InsufficientFundsException;
 public void balanceEnquiry();
}
HDFCBank.java
import com.pkr.exceptions.InsufficientFundsException;
import com.pkr.exceptions.InvalidAmountException;
public class HDFCBank implements Bank
{
 private double balance;
 public void deposite(double amount) throws InvalidAmountException 
 {
  if(amount <= 0)
  {
   throw new InvalidAmountException(amount + "is not valid");
  }
  balance = balance + amount;
 }
 public double withdraw(double amount) throws InsufficientFundsException 
 {
  if(balance < amount)
  {
   throw new InsufficientFundsException("insufficient funds");
  }
  balance = balance - amount;
  return amount;
 }
 public void balanceEnquiry() 
 {
  System.out.println("current balance = "+ balance);
 }
}
Cleark.java
package com.pkr.user;
import com.pkr.blogic.*;
import com.pkr.exceptions.*;
import java.util.*;
public class Clerk
{
 public static void main(String[] args) 
 {
  try
  {
   Scanner sc = new Scanner(System.in);
   Bank acc1 = new HDFCBank();
   String option = "";
   do
   {
    System.out.println("1. DEPOSITE");
    System.out.println("2. WITHDRAW");
    System.out.println("3. BALANCE ENQUIRY");
    System.out.println("ENTER OPTION");
    option = sc.next();
    switch(option)
    {
     case "1":
     {
      System.out.println("ENTER DEPOSIT AMOUNT");
      double amt = sc.nextDouble();
      acc1.deposite(amt);
      acc1.balanceEnquiry();
      break;
     }
     case "2":
     {
      System.out.println("ENTER WITHDRAW AMOUNT");
      double amt = sc.nextDouble();
      double wd = acc1.withdraw(amt);
    System.out.println("WITHDRAW AMOUNT IS :" + wd);
      acc1.balanceEnquiry();
      break;
     }
     case"3":
     {
      acc1.balanceEnquiry();
      break;
     }
     default:
      System.out.println("INVALID OPTION");
    }
    System.out.println("DO YOU WANT TO CONTINUE (YES/NO)");
    option = sc.next();
   }while(option.equalsIgnoreCase("YES"));
  }
  catch(InvalidAmountException iae)
  {
   System.out.println(iae.getMessage());
  }
  catch(InsufficientFundsException ife)
  {
   System.out.println(ife.getMessage());
  }
  catch(NumberFormatException nfe)
  {
   System.out.println(nfe.getMessage());
  }
 }
}
Advantages of Exception Handling

Separating Error-Handling Code from “Regular” Code: Exceptions provide the means to separate the details of what to do when something out of the ordinary happens from the main logic of a program.

Propagating Errors Up the Call Stack: Ability to propagate error reporting up the call stack of methods.

Grouping and Differentiating Error Types: Because all exceptions thrown within a program are objects, the grouping or categorizing of exceptions is a natural outcome of the class hierarchy.

In the next article, I am going to discuss Exception Propagation in Java with Examples. Here, in this article, I try to explain User-Defined or Custom Exception in Java with examples. I hope you enjoy this article. I would like to have your feedback. Please post your feedback, question, or comments about this article.

Leave a Reply

Your email address will not be published. Required fields are marked *