🎉 Special Offer !    Code: GET300OFF    Flat ₹300 OFF on every Java Course
Grab Deal 🚀

User-Defined Custom Exceptions in Java  


Introduction

  • Till now we have seen built-in exceptions in Java like IOException, NullPointerException, etc., and how to handle them using throw and throws.
  • But sometimes in real-world applications, we encounter situations where these built-in exceptions are not sufficient to describe specific error conditions.
  • For example, consider a banking application:
    • You want to throw an exception when a customer tries to withdraw more money than their account balance.
    • Java does not provide a built-in exception specifically for this scenario.
  • For such cases, user-defined exceptions (also called custom exceptions) are introduced.
  • Definition:
    • A user-defined exception in Java is an exception that is created by the programmer to represent a specific error scenario not covered by Java’s built-in exceptions.
      • It extends the Exception class (for checked exceptions) or the RuntimeException class (for unchecked exceptions).
      • It can include custom error messages and methods if needed.
  • Uses:
    • To represent application-specific errors clearly.
    • To make error handling more readable and meaningful.
    • To enforce business rules in an application (e.g., invalid transactions, age restrictions, invalid input).
    • To make debugging and maintenance easier by providing descriptive messages.
Steps to Create a User-Defined Exception
  1. Create a new class that extends Exception (for checked exceptions) or RuntimeException (for unchecked exceptions).
  2. Define constructors in your class (usually one default constructor and one that accepts a custom message).
  3. Use the throw keyword to throw the exception object in your code when the specific condition occurs.
  4. Handle the exception using try-catch or propagate it using throws.
Example :
  • // Step 1: Create a user-defined exception
    class InsufficientBalanceException extends Exception
    {
        // Constructor with custom message
        public InsufficientBalanceException(String message)
        {
            super(message);
        }
    }
    
    // Step 2: Use the custom exception in application
    class BankAccount
    {
        private double balance;
    
        public BankAccount(double balance)
        {
            this.balance = balance;
        }
    
        // Withdraw method which may throw the user-defined exception
        public void withdraw(double amount) throws InsufficientBalanceException
        {
            if(amount > balance)
            {
                throw new InsufficientBalanceException("Withdrawal failed: Insufficient balance!");
            }
            else
            {
                balance -= amount;
                System.out.println("Withdrawal successful. Remaining balance: " + balance);
            }
        }
    }
    
    public class MainApp
    {
        public static void main(String[] args)
        {
            BankAccount account = new BankAccount(5000);
    
            try
            {
                account.withdraw(6000); // Trying to withdraw more than balance
            }
            catch (InsufficientBalanceException e)
            {
                System.out.println("Exception caught: " + e.getMessage());
            }
    
            try
            {
                account.withdraw(3000); // Valid withdrawal
            }
            catch (InsufficientBalanceException e)
            {
                System.out.println("Exception caught: " + e.getMessage());
            }
        }
    }
  • Explanation:
    • InsufficientBalanceException is our user-defined exception.
    • It extends the Exception class, so it is a checked exception.
    • In the withdraw() method, we throw this exception if the withdrawal amount exceeds the balance.
    • In main(), we handle it using try-catch.
    • This approach makes the program clear, readable, and maintainable.