Skip to content
AgileLogics
4 min read

Custom Exceptions

Prerequisites: Exception handling

Extend Exception (checked) or RuntimeException (unchecked) to create an exception type specific to your program's domain:

class InsufficientFundsException extends RuntimeException {
    InsufficientFundsException(String message) {
        super(message);
    }
}

class BankAccount {
    private double balance;

    void withdraw(double amount) {
        if (amount > balance) {
            throw new InsufficientFundsException(
                "Cannot withdraw " + amount + "; balance is " + balance
            );
        }
        balance -= amount;
    }
}

A custom exception name that clearly states what went wrong (rather than a generic RuntimeException with just a message) lets calling code catch and react to that specific failure differently from others.