异常(取款不能大于余额)
/*2编写程序:实现到银行取款的金额不能超过银行的余额。
思路:
(1)定义一个异常类,名字为BankException。
(2)定义一个银行类,名字为Bank,里面有取款()方法,存款方法()。其中取款方法要声明为有可能为抛出BankException异常,在该方法的方法体内,要有明确的throw语句,抛出一个BankException对象。
(3)定义一个测试类,测试捕获这个异常。*/
class BankException extends Exception
{
BankException()
{
/*super("非常抱歉,银行的的余额小于您要取的金额!");*/
}
public void String()
{
System.out.println("非常抱歉,的余额小于您要取的金额");
}
}
class Bank
{
String name;
double money;
Bank(String name,double money)
{
this.name=name;
this.money=money;
}
public void QuKuan(double Qmoney) throws BankException
{
if(this.money<Qmoney)
{throw new BankException();}
else
{
this.money=this.money-Qmoney;
}
}
public void CunKuan(double Cmoney)
{
this.money=this.money+Cmoney;
}
}
public class BankExceptionTest
{
public static void main(String[] args)
{
Bank B1=new Bank("中国银行",20000);
B1.CunKuan(50000);
try
{B1.QuKuan(100000);}
catch(BankException e)
{e.String();}
}
}
运行效果:

浙公网安备 33010602011771号