定义一个银行取钱金额大于余额自定义异常,不能取钱时用throw抛出异常
时间: 2024-03-26 09:35:43 浏览: 71
好的,我理解了你的要求。以下是Java代码示例:
```java
public class InsufficientBalanceException extends Exception {
public InsufficientBalanceException(String message) {
super(message);
}
}
public class BankAccount {
private double balance;
public BankAccount(double balance) {
this.balance = balance;
}
public void withdraw(double amount) throws InsufficientBalanceException {
if (amount > balance) {
throw new InsufficientBalanceException("取款失败:余额不足");
}
balance -= amount;
System.out.println("成功取出 " + amount + " 元,余额为 " + balance + " 元");
}
}
```
`InsufficientBalanceException` 是自定义异常类,用于表示取钱金额大于余额的情况。当 `withdraw` 方法中检测到取款金额大于余额时,会抛出该异常。你可以按照以下方式使用 `BankAccount` 类:
```java
public static void main(String[] args) {
BankAccount account = new BankAccount(1000.0);
try {
account.withdraw(1200.0); // 尝试取出 1200 元
} catch (InsufficientBalanceException e) {
System.out.println(e.getMessage()); // 输出异常信息
}
}
```
当取款金额大于余额时,`withdraw` 方法会抛出 `InsufficientBalanceException` 异常,并且程序会输出异常信息 "取款失败:余额不足"。
阅读全文