☕ Java

Custom Exceptions in Java

Java's built-in exceptions cover generic failures — but your business logic has specific failure modes. InsufficientFundsException, InvalidAgeException, UserNotFoundException — these tell you exactly what went wrong, not just that 'something failed'.

Checked vs Unchecked Exceptions

Before creating custom exceptions, understand the two types: Checked Exceptions (extend Exception): • The compiler forces you to handle or declare them • Used for recoverable situations you can anticipate: file not found, network timeout, insufficient funds • The caller is warned: "this method can fail in this way — handle it" Unchecked Exceptions (extend RuntimeException): • Compiler doesn't force handling — they're typically programming errors • Used for bugs: NullPointerException, ArrayIndexOutOfBoundsException, IllegalArgumentException • Usually indicate something is fundamentally wrong in your code logic

Creating and Using a Custom Exception

Java
// Custom checked exception — extend Exception
public class InsufficientFundsException extends Exception {
    private final double shortfall;

    public InsufficientFundsException(double shortfall) {
        super("Transaction failed: insufficient funds. Shortfall: ₹" + shortfall);
        this.shortfall = shortfall;
    }

    public double getShortfall() { return shortfall; }
}

// Using the custom exception in a real class
public class BankAccount {
    private double balance;
    private final String owner;

    public BankAccount(String owner, double initialBalance) {
        this.owner = owner;
        this.balance = initialBalance;
    }

    // 'throws' declares that this method can throw this exception
    public void withdraw(double amount) throws InsufficientFundsException {
        if (amount > balance) {
            throw new InsufficientFundsException(amount - balance);
        }
        balance -= amount;
        System.out.println("Withdrew ₹" + amount + ". Remaining: ₹" + balance);
    }
}

// Calling code — compiler FORCES you to handle the checked exception
BankAccount acc = new BankAccount("Alice", 1000);
try {
    acc.withdraw(1500);  // This will throw
} catch (InsufficientFundsException e) {
    System.out.println(e.getMessage());
    System.out.println("You need ₹" + e.getShortfall() + " more");
}