//Bank类
package d0923;
public class Bank {
private double balance;
Bank(double a) {
balance += a;
}
void withDrawal(double dAmount) throws InsufficientFundsException, NagativeFundsException {
if(dAmount<0)
throw new InsufficientFundsException(dAmount);
if(dAmount>balance)
throw new NagativeFundsException();
System.out.println("取款:"+dAmount);
this.balance-=dAmount;
}
}
///InsufficientFundsException
package d0923;
public class InsufficientFundsException extends Exception {
InsufficientFundsException(double i)
{
System.out.println("发生错误:"+"取款额"+i+"为负数。");
}
}
///NagativeFundsException
package d0923;
public class NagativeFundsException extends Exception {
NagativeFundsException()
{
System.out.println("超出余额:");
}
}
package d0923;
public class NagativeFundsException extends Exception {
NagativeFundsException()
{
System.out.println("超出余额:");
}
}
//测试主类
package d0923;
public class TestBank {
public static void main(String[] args) {
Bank b=new Bank(100);
try{
b.withDrawal(-15);
}
catch(InsufficientFundsException e)
{
e.printStackTrace();
}
catch(NagativeFundsException e)
{
e.printStackTrace();
}
try{
b.withDrawal(150);
}
catch(InsufficientFundsException | NagativeFundsException e)
{
e.printStackTrace();
}
}
}
//运行结果
发生错误:取款额-15.0为负数。 ///withdrawal调用的构造函数
d0923.InsufficientFundsException
at d0923.Bank.withDrawal(Bank.java:12) /// printStack
at d0923.TestBank.main(TestBank.java:8)
超出余额:
d0923.NagativeFundsException
at d0923.Bank.withDrawal(Bank.java:14)
at d0923.TestBank.main(TestBank.java:20)