/** * 任务二:银行取款自定义异常 * 文件内含:InsufficientFundsException + Account + main 测试 */ // ── 自定义异常:继承 Exception(Checked,强迫调用方处理)── class InsufficientFundsException extends Exception { private final double balance; // 当前余额 private final double amount; // 尝试取款金额 public InsufficientFundsException(double balance, double amount) { super(String.format("余额不足!当前余额 %.2f 元,尝试取款 %.2f 元,差额 %.2f 元", balance, amount, amount - balance)); this.balance = balance; this.amount = amount; } public double getBalance() { return balance; } public double getAmount() { return amount; } } // ── Account 类 ── class Account { private final String owner; private double balance; public Account(String owner, double initialBalance) { this.owner = owner; this.balance = initialBalance; } /** * 取款:余额不足时抛出 InsufficientFundsException,并携带当前余额信息 */ public void withdraw(double amount) throws InsufficientFundsException { if (amount <= 0) { throw new IllegalArgumentException("取款金额必须大于 0"); } if (amount > balance) { throw new InsufficientFundsException(balance, amount); } balance -= amount; System.out.printf(" 取款成功:%.2f 元,剩余余额:%.2f 元%n", amount, balance); } public double getBalance() { return balance; } public String getOwner() { return owner; } } // ── 测试入口 ── public class BankAccount { public static void main(String[] args) { Account acc = new Account("张三", 500.00); System.out.println("账户:" + acc.getOwner() + ",初始余额:" + acc.getBalance()); // 正常取款 System.out.println("\n--- 取款 200 元 ---"); try { acc.withdraw(200); } catch (InsufficientFundsException e) { System.out.println(" 提示:" + e.getMessage()); } // 余额不足 System.out.println("\n--- 取款 400 元(余额不足)---"); try { acc.withdraw(400); } catch (InsufficientFundsException e) { System.out.println(" 提示:" + e.getMessage()); System.out.printf(" 当前余额:%.2f 元,建议最多取 %.2f 元%n", e.getBalance(), e.getBalance()); } // 非法金额 System.out.println("\n--- 取款 -50 元(非法金额)---"); try { acc.withdraw(-50); } catch (InsufficientFundsException e) { System.out.println(" 提示:" + e.getMessage()); } catch (IllegalArgumentException e) { System.out.println(" 错误:" + e.getMessage()); } } }