日期:2014-05-20  浏览次数:20654 次

初学问题:高分悬赏异常问题
有java简单实现:给客户建立一个帐户,当取钱大于余额时,就抛出异常,显示余额不足!

------解决方案--------------------
try{
if( 取钱大于余额 )
new Exception( "余额不足! ");
}catch(Exception msg){
System.out.println(msg.getMessage());
}
------解决方案--------------------
更标准的做法是把余额不足这个错误定义成一个MoneyNotEnoughException

public void fetchMoney(int money) throws MoneyNotEnoughException,Exception{
if ...{
throw new MoneyNotEnoughException( "余额不足! ");
}
}

外部调用fetchMoney()时用try取得错误
try{
fetchMoney(1000)
}
catch(MoneyNotEnoughException e1){
...println( "余额不足! ")
}
catch(Exception e){
e.printStackTrace();
}

------解决方案--------------------
public class MoneyNotEnough extends Exception {

public MoneyNotEnough() {
super();
}

/**
* @param message
* @param cause
*/
public MoneyNotEnough(String message, Throwable cause) {
super(message, cause);
}

/**
* @param message
*/
public MoneyNotEnough(String message) {
super(message);
}

/**
* @param cause
*/
public MoneyNotEnough(Throwable cause) {
super(cause);
}

}

public class Account{

private long nowMoney ;

Account(){ nowMoney = 5000; }

public boolean hasEnoughMoney(long out) throws MoneyNotEnough{

if (out > this.nowMoney) throw new MoneyNotEnough( "余额不足 ");

nowMoney = nowMoney - out;
return true;

}
}