While the standard Java runtime library provides dozens of built-in exception types, enterprise applications require domain-specific custom exceptions (e.g. InsufficientFundsException, InvalidAadhaarNumberException) to communicate business rule violations clearly.
// Custom Checked Exception: Extends Exception
public class InsufficientFundsException extends Exception {
private double attemptedAmount;
private double currentBalance;
// Standard constructor passing descriptive message to superclass
public InsufficientFundsException(String message, double attempted, double current) {
super(message);
this.attemptedAmount = attempted;
this.currentBalance = current;
}
// Custom getters for detailed diagnostic reporting
public double getAttemptedAmount() { return attemptedAmount; }
public double getCurrentBalance() { return currentBalance; }
}
public class BankAccount {
private double balance = 5000.0;
public void withdraw(double amount) throws InsufficientFundsException {
if (amount > balance) {
// Throw custom exception with domain diagnostics
throw new InsufficientFundsException(
"Withdrawal rejected: Overdraft limit exceeded!",
amount,
balance
);
}
balance -= amount;
System.out.println("Withdrawal approved. Remaining balance: $" + balance);
}
public static void main(String[] args) {
BankAccount acc = new BankAccount();
try {
acc.withdraw(7500.0); // Fails!
} catch (InsufficientFundsException e) {
System.err.println("Transaction Failed: " + e.getMessage());
System.err.println("Attempted: $" + e.getAttemptedAmount());
System.err.println("Available: $" + e.getCurrentBalance());
}
}
}
Exam Question: "What is the difference between creating a custom exception extending Exception vs RuntimeException?"
Answer: Extending Exception creates a Checked Exception: callers must either handle it with try-catch or declare it on their methods with throws. Extending RuntimeException creates an Unchecked Exception: it can be thrown without requiring any compile-time throws declaration.
Now let us explore Automatic Resource Management with Try-with-Resources. Proceed to: Java Try-with-Resources →
Accelerate your Java mastery by studying these tightly connected core tutorials:
Checked vs unchecked architecture.
Throwing custom exception objects.
Catching custom exceptions.
Resource management.