zoukankan      html  css  js  c++  java
  • Java 异常处理 练习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 {
    
         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 "余额不足";
         }
    }

  • 相关阅读:
    487-3279(电话号码)
    【模板】二分图匹配
    【模板】网络最大流
    P3879 [TJOI2010]阅读理解
    10.10 考试T1 低仿机器人
    P4025 [PA2014]Bohater
    线段树合并 从入门到入土
    CF547B Mike and Feet
    10.6洛谷月赛划水记
    P4552 [Poetize6] IncDec Sequence
  • 原文地址:https://www.cnblogs.com/chouji717/p/5915088.html
Copyright © 2011-2022 走看看