Java Custom Exceptions: Creating Robust User-Defined Exceptions

While the standard Java runtime library provides dozens of built-in exception types, enterprise applications require domain-specific custom exceptions (e.g. InsufficientFundsException, InvalidAadhaarNumberException) to communicate business rule violations clearly.

Step 1: Defining the Custom Exception Class

// Custom Checked Exception: Extends Exception
public class InsufficientFundsException extends Exception {
    private double attemptedAmount;
    private double currentBalance;

    // Standard constructor passing descriptive message to superclass
    public InsufficientFundsException(String message, double attempted, double current) {
        super(message);
        this.attemptedAmount = attempted;
        this.currentBalance = current;
    }

    // Custom getters for detailed diagnostic reporting
    public double getAttemptedAmount() { return attemptedAmount; }
    public double getCurrentBalance() { return currentBalance; }
}

Step 2: Throwing and Catching in Business Logic

public class BankAccount {
    private double balance = 5000.0;

    public void withdraw(double amount) throws InsufficientFundsException {
        if (amount > balance) {
            // Throw custom exception with domain diagnostics
            throw new InsufficientFundsException(
                "Withdrawal rejected: Overdraft limit exceeded!", 
                amount, 
                balance
            );
        }
        balance -= amount;
        System.out.println("Withdrawal approved. Remaining balance: $" + balance);
    }

    public static void main(String[] args) {
        BankAccount acc = new BankAccount();
        try {
            acc.withdraw(7500.0); // Fails!
        } catch (InsufficientFundsException e) {
            System.err.println("Transaction Failed: " + e.getMessage());
            System.err.println("Attempted: $" + e.getAttemptedAmount());
            System.err.println("Available: $" + e.getCurrentBalance());
        }
    }
}

University Exam Corner (BCA / B.Sc CS)

Exam Question: "What is the difference between creating a custom exception extending Exception vs RuntimeException?"

Answer: Extending Exception creates a Checked Exception: callers must either handle it with try-catch or declare it on their methods with throws. Extending RuntimeException creates an Unchecked Exception: it can be thrown without requiring any compile-time throws declaration.

Next Step

Now let us explore Automatic Resource Management with Try-with-Resources. Proceed to: Java Try-with-Resources →

Frequently Asked Questions (FAQ)

Q1. Why do we need Custom Exceptions in Java?
Standard built-in Java exceptions (like IllegalArgumentException) are generic. Custom exceptions provide clear domain-specific meaning (e.g. InsufficientBalanceException, UserNotFoundException), allowing business logic to catch and recover from distinct application failure states.
Q2. How do you create a Checked Custom Exception vs an Unchecked Custom Exception?
To create a Checked custom exception, extend 'java.lang.Exception'. To create an Unchecked custom exception, extend 'java.lang.RuntimeException'.
Q3. What constructors should every custom exception include?
Best practice is to provide at least 4 standard constructors: a no-arg constructor, a message constructor (String message), a cause constructor (Throwable cause), and a combined message and cause constructor.

Explore Related Java Tutorials

Accelerate your Java mastery by studying these tightly connected core tutorials:

Exception Hierarchy →

Checked vs unchecked architecture.

Throw vs Throws →

Throwing custom exception objects.

Try, Catch & Finally →

Catching custom exceptions.

Try-with-Resources →

Resource management.

Share Share on Facebook Share on Twitter Share on LinkedIn Pin on Pinterest Share on Stumbleupon Share on Tumblr Share on Reddit Share on Diggit

You may also like this!