mirror of
https://github.com/Dichgrem/Java.git
synced 2026-02-05 02:51:57 -05:00
38 lines
888 B
Java
38 lines
888 B
Java
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());
|
|
}
|
|
}
|
|
}
|