异常处理2

建立exception包,建立Bank类,类中有变量double balance表示存款,Bank类的构造方法能增加存款,Bank类中有取款的发方法withDrawal(double dAmount),当取款的数额大于存款时,抛出InsufficientFundsException,取款数额为负数,抛出NagativeFundsException,如new Bank(100),表示存入银行100元,当用方法withdrawal(150),withdrawal(-15)时会抛出自定义异常。

package exception;



public class Bank {
    
    double balance;
    
    Bank(double cunkuan)
    {
        this.balance+=cunkuan;
        System.out.println("您存了"+cunkuan+"元,当前余额为:"+this.balance);
    }
    
    void withDrawal(double dAmount) throws Exception
    {
        
        if(dAmount>this.balance)
        {
            throw new InsufficientFundsException();
        }
        
        if(dAmount<0)
        {
            throw new NagativeFundsException();
        }
        this.balance-=dAmount;
        System.out.println("您取了"+dAmount+"元,当前余额为:"+this.balance);
    }
    
    public static void main(String args[]) 
    {
        Bank bb=new Bank(100);
        
        
            try {
                bb.withDrawal(23);
            } catch (Exception e1) {
                // TODO 自动生成的 catch 块
                e1.printStackTrace();
            }
        
        //取款金额为负
            try {
                bb.withDrawal(-6);
            } catch (Exception e) {
                // TODO 自动生成的 catch 块
                e.printStackTrace();
            }
            
        //取款金额大于存款
        
            try {
                bb.withDrawal(150);
            } catch (Exception e) {
                // TODO 自动生成的 catch 块
                e.printStackTrace();
            }
                
            
        
            
    }
    
    
    

}
package exception;

public class InsufficientFundsException extends Exception {

    @Override
    public String getMessage() {
        // TODO 自动生成的方法存根
        return "余额不足";
    }

    
    
}
package exception;

public class NagativeFundsException extends Exception {

    @Override
    public String getMessage() {
        // TODO 自动生成的方法存根
        return "取款额不能为负";
    }

    
    
    
}

运行结果:

posted @ 2016-05-28 14:06  鱼在我这里  阅读(162)  评论(0编辑  收藏  举报