Skip to main content

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.

  1. If you haven't already done so, complete the L06 Bank Account lab.
  2. Create an InsufficientFunds exception class that consists of the following statements:
public class InsufficientFunds extends RuntimeException { 
  public InsufficientFunds() { } 
  public InsufficientFunds(String msg) { 
    super(msg); //use superclass RuntimeException constructor 
  } 
}
  1. Modify the withdraw method in the BankAccount class to compare the amount to the balance and throw an InsufficientFunds exception 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; 
  } 
}
  1. Modify the BankAccountTest program so that it handles an InsufficientFunds exception:
... 
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!"); 
  } 
} ...
  1. Execute the BankAccountTest program 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!