A custom exception (also called a user-defined exception) is an exception class created by a developer to represent specific errors.
Why Use Custom Exceptions?
Naming an error
InsufficientFundsExceptionimmediately tells other developers what went wrong, whereas a genericExceptionrequires reading through error messages to understand the issue.
# 1. Define the custom exception class
class InsufficientFundsException extends Exception {
public InsufficientFundsException(String message) {
super(message); # Pass the error message to the parent Exception class
}
}
# 2. Throw and catch it in your application
public class BankAccount {
private double balance = 100.0;
public void withdraw(double amount) throws InsufficientFundsException {
if (amount > balance) {
throw new InsufficientFundsException("Balance too low to withdraw $" + amount);
}
balance -= amount;
}
public static void main(String[] args) {
BankAccount account = new BankAccount();
try {
account.withdraw(150.0);
} catch (InsufficientFundsException e) {
System.out.println("Transaction failed: " + e.getMessage());
}
}
}