L11 - Designing Exception Types Lab
In this lab, we'll create our own exception class for the BankAccount class to handle the case where a customer tries to withdraw more money than they have in their account.
- If you haven't already done so, complete the L06 Bank Account lab.
- Create an
InsufficientFundsexception class that consists of the following statements:
public class InsufficientFunds extends RuntimeException {
public InsufficientFunds() { }
public InsufficientFunds(String msg) {
super(msg); //use superclass RuntimeException constructor
}
}
- Modify the withdraw method in the
BankAccountclass to compare the amount to the balance and throw anInsufficientFundsexception if there isn't enough money:
public void withdraw(double amount) {
if (amount <= balance) balance -= amount;
else {
InsufficientFunds myEx;
myEx = new InsufficientFunds("Amount exceeds balance");
throw myEx;
}
}
- Modify the
BankAccountTestprogram so that it handles anInsufficientFundsexception:
...
else if (menuChoice.equalsIgnoreCase("W")) {
try {
System.out.print("Enter amount: ");
String answer = myScanner.nextLine();
amount = Double.parseDouble(answer);
myChecking.withdraw(amount);
}
catch (InsufficientFunds myEx) {
System.out.println(myEx.getMessage());
System.out.println("Transaction aborted!");
}
} ...
- Execute the
BankAccountTestprogram using values that does not and does trigger the withdraw exception.
Sample Dialog
Enter initial checking account balance: 500
D - Deposit into checking
W - Withdraw from checking
P - End of month processing
S - Show account balance
E - Exit the program
>W
Enter amount: 100
>S
Checking balance: 400.0
>W
Enter amount: 1000
Amount exceeds balance Transaction aborted!
>e
Goodbye!
No Comments