mirror of
https://github.com/Dichgrem/Java.git
synced 2026-02-05 02:51:57 -05:00
update:demo7
This commit is contained in:
37
com/study/demo7/BankWithdraw.java
Normal file
37
com/study/demo7/BankWithdraw.java
Normal file
@@ -0,0 +1,37 @@
|
||||
package com.study.demo7;
|
||||
|
||||
// 自定义异常
|
||||
class InsufficientBalanceException extends Exception {
|
||||
public InsufficientBalanceException(String message) {
|
||||
super(message);
|
||||
}
|
||||
}
|
||||
|
||||
// 账户类
|
||||
class Account {
|
||||
private double balance;
|
||||
|
||||
public Account(double balance) {
|
||||
this.balance = balance;
|
||||
}
|
||||
|
||||
public void withdraw(double amount) throws InsufficientBalanceException {
|
||||
if (amount > balance) {
|
||||
throw new InsufficientBalanceException("余额不足,当前余额: " + balance);
|
||||
}
|
||||
balance -= amount;
|
||||
System.out.println("取款成功,剩余余额: " + balance);
|
||||
}
|
||||
}
|
||||
|
||||
// 主类
|
||||
public class BankWithdraw {
|
||||
public static void main(String[] args) {
|
||||
Account account = new Account(1000.0);
|
||||
try {
|
||||
account.withdraw(100.0);
|
||||
} catch (InsufficientBalanceException e) {
|
||||
System.out.println("取款失败: " + e.getMessage());
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user