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.
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());
}
InsufficientFundsException: need 100 but have 50
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