Extending Exception for Checked Exceptions
What You'll Learn
You'll learn how to create your own custom checked exceptions by extending the Exception class, forcing callers to handle your domain-specific error conditions at compile time.
Why Extend Exception?
Sometimes the built-in exceptions like IOException or SQLException don't precisely capture the specific problems in your application domain. By creating custom checked exceptions, you can give meaningful names to error conditions and force callers to acknowledge and handle them.
Creating a Custom Checked Exception
To create a checked exception, simply extend the Exception class:
public class InsufficientFundsException extends Exception {
public InsufficientFundsException(String message) {
super(message);
}
}
By extending Exception (not RuntimeException), you create a checked exception that must be declared with throws or handled with try-catch.
Forcing Callers to Handle It
When you throw your custom checked exception, the compiler enforces handling:
public void withdraw(double amount) throws InsufficientFundsException {
if (amount > balance) {
throw new InsufficientFundsException("Cannot withdraw: balance too low");
}
balance -= amount;
}
Now any caller of withdraw must either catch InsufficientFundsException or declare it in their own throws clause. The compiler won't let them ignore this exceptional condition.
Think of It as a Contract
Creating a custom checked exception is like putting up a warning sign: "This method can fail in this specific way, and you must plan for it." It's especially useful for recoverable business logic errors where the caller should make an informed decision about how to proceed.
Key Takeaway:
Extending Exception creates a custom checked exception that the compiler forces callers to handle, making domain-specific error conditions explicit and impossible to ignore.