import java.util.Scanner; // Custom Exception: InsufficientFundsException class InsufficientFundsException extends Exception { public InsufficientFundsException(double balance, double amount) { super("Insufficient funds: Tried to withdraw " + amount + ", but balance is only " + balance + "."); } } // Custom Exception: NegativeAmountException class NegativeAmountException extends Exception { public NegativeAmountException(double amount) { super("Invalid amount: Withdrawal amount cannot be negative (" + amount + ")."); } } // BankAccount Class class BankAccount { private double balance; // Constructor to initialize the account balance public BankAccount(double balance) { this.balance = balance; } // Method to withdraw money public void withdraw(double amount) throws InsufficientFundsException, NegativeAmountException { if (amount < 0) { throw new NegativeAmountException(amount); } else if (amount > balance) { throw new InsufficientFundsException(balance, amount); } else { balance -= amount; System.out.println("Withdrawal successful! New balance: " + balance); } } // Getter for balance public double getBalance() { return balance; } } // Main Class public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); // Initialize BankAccount with a starting balance BankAccount account = new BankAccount(100); // You can set a different starting balance if needed while (true) { System.out.println("\nCurrent balance: " + account.getBalance()); System.out.print("Enter amount to withdraw (or type 'exit' to quit): "); // Check if the input is 'exit' to terminate the loop if (scanner.hasNext("exit")) { System.out.println("Exiting..."); break; } // Try to parse the amount as a double try { double amount = scanner.nextDouble(); // Attempt to withdraw and handle potential exceptions try { account.withdraw(amount); } catch (InsufficientFundsException | NegativeAmountException e) { System.out.println(e.getMessage()); } } catch (Exception e) { // Handle invalid input (non-numeric) System.out.println("Invalid input. Please enter a numeric amount."); scanner.next(); // Clear the invalid input } } scanner.close(); // Close the scanner resource } }