您的位置:首页 > 其它

异常3

2016-05-28 13:26 369 查看
建立Bank类,类中有变量double balance表示存款,Bank类的构造方法能初始化余额,Bank类中有存款的方法cunKuan(double balance),取款的发方法withDrawal(double dAmount),当取款的数额大于存款时,抛出InsufficientFundsException,取款数额为负数,抛出NagativeFundsException,当用方法withdrawal(150),withdrawal(-15)时会抛出自定义异常。

public class Bank {
double yu_e;
double balance;

Bank(double yu_e) {
this.yu_e = yu_e;
System.out.println("账户内余额:"+this.yu_e+"元");
}

void cunKuan(double balance) throws Exception {
if(balance<0){
throw new Exception("存款不能为负");
}
yu_e += balance;
}

void withDrawal(double dAmount) throws Exception {
if(dAmount>yu_e){
throw new Exception("InsufficientFundsException,余额不足");
}else if (dAmount<0){
throw new Exception("NagativeFundsException,取款值为负");
}
yu_e -= dAmount;
}

public static void main(String[] args) {

Bank b = new Bank(10);
try {
b.cunKuan(-100);
} catch (Exception e) {
e.printStackTrace();
}

try {
b.withDrawal(150);
} catch (Exception e) {
e.printStackTrace();
}

try {
b.withDrawal(-15);
} catch (Exception e) {
e.printStackTrace();
}

System.out.println("存款余额"+b.yu_e+"元");

}

}


运行:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: