建立exception包,建立Bank类,类中有变量double balance表示存款,Bank类的构造方法能增加存款,Bank类中有取款的发方法withDrawal(double dAmount),当取款的数额大于存款时,抛出InsufficientFundsException,取款数额为负数,抛出NagativeFundsException,如new Bank(100),表示存入银行1

//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)

原文地址:https://www.cnblogs.com/smile-dream/p/5915448.html