📄 exceptiondemo.java~1~
字号:
package exceptiondemo;
/**
例2 :在定义银行类时,若取钱数大于余额则作为异常处理(InsufficientFundsException).
思路:产生异常的条件是余额少于取额, 因此是否抛出异常要判断条件
取钱是withdrawal方法中定义的动作,因此在该方法中产生异常.
处理异常安排在调用withdrawal的时候,因此withdrawal方法要声明异常,由上级方法调用
要定义好自己的异常类
*/
class Bank {
double balance;
public void deposite(double dAmount) {
if (dAmount > 0.0) {
balance += dAmount;
}
}
public void withdrawal(double dAmount) throws InsufficientFundsException {
if (balance < dAmout) {
throw new InsufficientFundsException(this, dAmount);
}
balance = balance - dAmount;
}
public void show_balance() {
System.out.println("The balance is " + (int) balance);
}
}
public class InsufficientFundsException extends Exception
{ private Bank excepbank;
private double excepAmount;
InsufficientFundsException(Bank ba, double dAmount)
{ excepbank=ba;
excepAmount=dAmount;
}
public String excepMesagge()
{ String str="The balance"+ excepbank.showBalance()+
"The withdrawal was"+excepAmount;
return str; }
public class ExceptionDemo {
public static void main(String args[]) {
try {
Bank ba = new Bank(50);
ba.withdrawal(100);
System.out.println("Withdrawal successful!");
}
catch (Exception e) {
System.out.println(e.toString());
}
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -