码迷,mamicode.com
首页 > 编程语言 > 详细

Java 异常处理 练习2

时间:2016-09-28 10:05:51      阅读:161      评论:0      收藏:0      [点我收藏+]

标签:

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

 

package exception;

public class Bank {

     private double balance;

        public Bank (double balance) {
            super();
            this.balance = balance;
        }
        public void withDrawal(double dAmount)throws InsufficientFundsException,NagativeFundsException
        {
            if(dAmount>balance)
            {
                throw new InsufficientFundsException();
            }
            if(dAmount<0)
            {
                throw new NagativeFundsException(); 
            }
        }
        
        public static void main(String[] args){
            Bank t=new Bank (100);
            try{
            t.withDrawal(110);
            }catch(Exception e){
                e.printStackTrace();
            }
            try{
                t.withDrawal(-100);
            }catch(Exception e){
                e.printStackTrace();
            }
        }
    
}
package exception;

public class NagativeFundsException extends Exception {
        
    public String getMessage()
     {
         return "取款不能为负数";
     }
}
package exception;

public class InsufficientFundsException extends Exception {

    public String getMessage()
     {
         return "余额不足";
     }
}

技术分享

Java 异常处理 练习2

标签:

原文地址:http://www.cnblogs.com/chouji717/p/5915088.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!