Custom exceptions are ideal when built-in Java exceptions do not accurately represent a business-specific error condition. They allow developers to create meaningful, domain-focused error handling, making the code easier to understand, maintain, and troubleshoot.
Key Points: • Custom exceptions clearly represent business rule violations instead of using generic exceptions. • They improve code readability by making error scenarios self-explanatory. • They enable more precise exception handling and better communication between application layers.
Example: In a banking system, if a customer tries to withdraw more money than the available balance, throwing an InsufficientFundsException is much more meaningful than using a generic IllegalArgumentException or Exception. The custom exception immediately tells developers and support teams what business rule was violated.
Code Example:
class InsufficientFundsException extends Exception {
public InsufficientFundsException(String message) {
super(message);
}
}
class BankAccount {
private double balance = 5000;
public void withdraw(double amount)
throws InsufficientFundsException {
if (amount > balance) {
throw new InsufficientFundsException(
"Insufficient account balance");
}
balance -= amount;
}
}
public class Main {
public static void main(String[] args) {
BankAccount account = new BankAccount();
try {
account.withdraw(10000);
} catch (InsufficientFundsException e) {
System.out.println(e.getMessage());
}
}
}Interview Tip: A concise interview answer is: Custom exceptions should be used when handling business-specific errors that built-in exceptions cannot clearly represent. For example, exceptions such as InsufficientFundsException, InvalidOrderException, or UserNotAuthorizedException make error handling more meaningful, maintainable, and easier to debug.