Core Java Fundamentals ยท Exception Handling
Make your own exception type, throw it when a rule is broken, and make callers handle it with throws.
class InsufficientFundsException extends Exception {
InsufficientFundsException(String message) {
super(message);
}
}
public class CustomExceptionDemo {
static double withdraw(double balance, double amount) throws InsufficientFundsException {
if (amount > balance) {
throw new InsufficientFundsException("Need " + (amount - balance) + " more");
}
return balance - amount;
}
public static void main(String[] args) {
double balance = 100;
try {
balance = withdraw(balance, 30);
balance = withdraw(balance, 500);
} catch (InsufficientFundsException e) {
System.out.println("Refused: " + e.getMessage());
}
System.out.println("Balance: " + balance);
}
}main. args holds its command-line arguments (none here). balance is created on the stack with the value 100.amount > balance to decide which way the code goes.withdraw() has finished, so its variables are gone.balance.withdraw(), with balance = 70 and amount = 500. It gets its own variables on the stack.backtrace in the InsufficientFundsException object changes from null to an Object[]. detailMessage in the InsufficientFundsException object changes from null to "Need 430.0 more". cause in the InsufficientFundsException object changes from null to an InsufficientFundsException. stackTrace in the InsufficientFundsException object changes from null to a StackTraceElement[].InsufficientFundsException() has finished, so its variables are gone.withdraw() has finished, so its variables are gone.e goes out of scope and disappears. It prints Refused: Need 430.0 more.Balance: 70.0.