Exceptions: a custom checked exception forces every caller to handle it

Extending Exception (not RuntimeException) makes a custom exception checked, so any method that throws it must declare it and any caller must either catch it or propagate it, enforced entirely at compile time.

Code
class InsufficientFundsException extends Exception {
    InsufficientFundsException(String message) {
        super(message);
    }
}
class Account {
    static void withdraw(int balance, int amount) throws InsufficientFundsException {
        if (amount > balance) {
            throw new InsufficientFundsException("need " + amount + " but have " + balance);
        }
    }
}
try {
    Account.withdraw(50, 100);
} catch (InsufficientFundsException e) {
    System.out.println(e.getClass().getSimpleName() + ": " + e.getMessage());
}
Output
InsufficientFundsException: need 100 but have 50
Advertisement
More in JAVA

Run this yourself in the Online Java Compiler, spin up a live REST API in the API Sandbox, or practise with Java interview questions.

Published 2026-09-27

© Java Coding Hub · About · Contact · Privacy · Terms