0、目录
1、练习:异常综合1
这是一个类图
Account类: 银行账号
属性: balance 余额
方法: getBalance() 获取余额
方法: deposit() 存钱
方法: withdraw() 取钱
OverdraftException: 透支异常,继承Exception
属性: deficit 透支额
public class Account {
protected double balance; // 余额
public Account(double balance) {
this.balance = balance;
}
public double getBalance() {
return balance;
}
// 存钱
public double deposit(double amt) {
return balance += amt;
}
// 取钱
public double withdraw(double amt) throws OverDraftException {
if (balance < amt) { // 若取钱金额超过余额,则会抛出异常,并根据自定义异常返回透支额
throw new OverDraftException("您的余额为不足,您当前透支额为: " + (amt - balance), amt - balance);
}
return balance -= amt;
}
public static void main(String[] args) {
Account money = new Account(5000);
System.out.println("您的账户当前余额为:" + money.getBalance());
money.deposit(3000);
System.out.println("您的账户当前余额为:" + money.getBalance());
try {
money.withdraw(10000);
} catch (OverDraftException e) {
System.err.println("您的账户透支金额为:" + e.getDeficit());
e.printStackTrace();
}
}
}
//自定义异常
public class OverDraftException extends Exception{
private double deficit; // 透支额
public OverDraftException(String message,double deficit) {
super(message);
this.deficit = deficit;
}
public double getDeficit() {
return deficit;
}
}
2、练习:异常综合2
类: CheckingAccount 支票账户,具备透支额度,继承Account
属性:overdraftProtection 透支额度
public class CheckingAccount extends Account {
private double overDraftProtection; // 透支额度
public CheckingAccount(double balance) {
super(balance); // 显式调用父类带参构造方法
}
public CheckingAccount(double balance, double overDraftProtection) {
super(balance); // 显式调用父类带参构造方法
this.overDraftProtection = overDraftProtection; // 将局部变量传入成员变量中
}
public double withdraw(double amt) throws OverDraftException {
if (balance + overDraftProtection < amt) { // 若取钱金额超过余额+透支额,则会抛出异常,并根据自定义异常返回透支额
throw new OverDraftException("您的余额为不足,您当前透支额为: " + (amt - balance - overDraftProtection),
amt - balance - overDraftProtection);
}
return balance -= amt;
}
public static void main(String[] args) {
// 拥有5000余额和250透支额度
CheckingAccount money = new CheckingAccount(5000, 2500);
// 存钱
money.deposit(3000);
// 显示余额
System.out.println("您的账户当前余额为:" + money.getBalance());
// 取钱
try {
for (int i = 0; i < Integer.MAX_VALUE; i++) {
money.withdraw(550);
System.out.println("取出550元,您的账户当前余额为: " + money.getBalance());
}
} catch (OverDraftException e) {
System.err.println("您的账户透支金额为:" + e.getDeficit());
e.printStackTrace();
}
}
}