How do you create a custom exception in Java?
Extend Exception for a checked custom exception or RuntimeException for an unchecked one, and add constructors that pass the message and optionally a cause to the parent. Use it to express a business rule clearly.
Explain it simply
A built-in exception like IllegalArgumentException is a generic "something is wrong" letter. A custom exception such as InsufficientBalanceException is a letter with a clear heading, so whoever receives it knows exactly which rule was broken.
Example
class InsufficientBalanceException extends Exception { // checked
private final double shortBy;
InsufficientBalanceException(String msg, double shortBy) {
super(msg);
this.shortBy = shortBy;
}
double getShortBy() { return shortBy; }
}
static void pay(double balance, double bill) throws InsufficientBalanceException {
if (bill > balance) throw new InsufficientBalanceException("Low balance", bill - balance);
}
try {
pay(200, 350);
} catch (InsufficientBalanceException e) {
System.out.println(e.getMessage() + ", short by " + e.getShortBy());
// prints: Low balance, short by 150.0
}What to say in the interview
"I extend Exception if callers should be forced to handle the problem, and RuntimeException if it signals a programming or unrecoverable error. I provide a constructor taking a message and another taking a message and a cause, so the original exception is not lost. I name the class after the problem and end it with Exception."
Common mistakes
- Extending Throwable directly.
- Dropping the original cause when wrapping another exception.