class InsufficientFundsException extends Exception {
private Bank excepbank; // 银行对象
private double excepAmount; // 要取的钱
InsufficientFundsException(Bank ba, double dAmount) {
excepbank = ba;
excepAmount = dAmount;
}
public String excepMessage() {
String str = "The balance is" + excepbank.balance + "\n"
+ "The withdrawal was" + excepAmount;
return str;
}
}
class Bank {
double balance;// 存款数
Bank(double balance) {
this.balance = balance;
}
public void deposite(double dAmount) {
if (dAmount > 0.0)
balance += dAmount;
}
public void withdrawal(double dAmount) throws InsufficientFundsException {
if (balance < dAmount)
throw new InsufficientFundsException(this, dAmount);
balance = balance - dAmount;
}
public void showBalance() {
System.out.println("The balance is " + (int) balance);
}
}
public class ExceptionDemo {
public static void main(String[] args) {
try {
Bank ba = new Bank(50);
ba.withdrawal(100); ba.showBalance();
System.out.println("Withdrawal successful!");
} catch (InsufficientFundsException e) {
e.printStackTrace();
System.out.println(e.excepMessage());
}
}
}
------解决方案--------------------
this代码Bank这个类的对象。
或者你可以吧这个对象在外面定义,然后传进来代替this
------解决方案--------------------
this在Bank类里面用的,代表bank对象。
------解决方案--------------------
代表当前你的类。
------解决方案--------------------
当前操作对象