Browse Source

添加 w7 自定义异常与银行取款练习

main
wangjiashuo 3 weeks ago
parent
commit
c150d21869
  1. BIN
      w7/BankWithdrawalTest$Account.class
  2. BIN
      w7/BankWithdrawalTest$InsufficientFundsException.class
  3. BIN
      w7/BankWithdrawalTest.class
  4. 66
      w7/BankWithdrawalTest.java

BIN
w7/BankWithdrawalTest$Account.class

Binary file not shown.

BIN
w7/BankWithdrawalTest$InsufficientFundsException.class

Binary file not shown.

BIN
w7/BankWithdrawalTest.class

Binary file not shown.

66
w7/BankWithdrawalTest.java

@ -0,0 +1,66 @@
public class BankWithdrawalTest {
static class InsufficientFundsException extends Exception {
private double balance;
public InsufficientFundsException(double balance) {
super("余额不足,当前余额:" + balance + " 元");
this.balance = balance;
}
public double getBalance() {
return balance;
}
}
static class Account {
private double balance;
public Account(double initialBalance) {
this.balance = initialBalance;
}
public void withdraw(double amount) throws InsufficientFundsException {
if (amount <= 0) {
throw new IllegalArgumentException("取款金额必须大于0");
}
if (amount > balance) {
throw new InsufficientFundsException(balance);
}
balance -= amount;
System.out.println("取款成功!取出:" + amount + " 元,剩余余额:" + balance + " 元");
}
public double getBalance() {
return balance;
}
}
public static void main(String[] args) {
Account myAccount = new Account(1000.0);
System.out.println("--- 测试1:正常取款 ---");
try {
myAccount.withdraw(300);
} catch (InsufficientFundsException e) {
System.out.println("错误:" + e.getMessage());
}
System.out.println("\n--- 测试2:余额不足取款 ---");
try {
myAccount.withdraw(800);
} catch (InsufficientFundsException e) {
System.out.println("取款失败:" + e.getMessage());
System.out.println("提示:请检查取款金额,当前账户余额为 " + e.getBalance() + " 元");
}
System.out.println("\n--- 测试3:非法金额取款 ---");
try {
myAccount.withdraw(-50);
} catch (IllegalArgumentException e) {
System.out.println("错误:" + e.getMessage());
} catch (InsufficientFundsException e) {
System.out.println("取款失败:" + e.getMessage());
}
}
}
Loading…
Cancel
Save