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 {
    //	中有变量double balance表示存款,
    //	Bank类的构造方法能增加存款,
    //	Bank类中有取款的发方法withDrawal(double dAmount),
    //	当取款的数额大于存款时,抛出InsufficientFundsException,
    //	取款数额为负数,抛出NagativeFundsException,
    	double balance;
    
    	public double getBalance() {
    		return balance;
    	}
    
    	public void setBalance(double balance) {
    		this.balance = balance;
    	}
    
    	public Bank(double balance)
    	{
    		System.out.println("存款金额为:"+(balance)); 
    	}
    	public void withDrawal(double dAmount)
    	{
    		if(dAmount>balance)
    		{
    			try {
    				throw new InsufficientFundsException();
    			    }
    			catch (InsufficientFundsException e) 
    			{
    				e.printStackTrace();
    			}
    			
    		}
    		if(dAmount<0)
    		{
    			try {
    				throw new NagativeFundsException();
    			} catch (NagativeFundsException e) {
    				
    				e.printStackTrace();
    			}
    			
    		}
    		
    	}
    }
    
    package exception;
    
    public class InsufficientFundsException extends Exception {
    
    	@Override
    	public String getMessage() {
    		
    		return "存款余额不足!";
    	}
    	
    	
    	
    
    }
    
    package exception;
    
    public class NagativeFundsException extends Exception {
    
    	@Override
    	public String getMessage() {
    		
    		return "取款数额不能为负数!";
    	}
    
    }
    
    package exception;
    
    public class test {
    
    	public static void main(String[] args) {
    		// TODO 自动生成的方法存根
    //		new Bank(100),表示存入银行100元,
    //		当用方法withdrawal(150),
    //		withdrawal(-15)时会抛出自定义异常
    		Bank b=new Bank(100);
    		
    		b.withDrawal(150);
    		b.withDrawal(-15);
    		
    
    	}
    
    }
    

     

  • 相关阅读:
    数组实现栈
    栈应用实例单词逆序
    使用JXMapViewer将地图集成到swing app中
    使用xbee连接地面站和飞控
    QWT编译、配置、使用(Qt Creator)
    Qt跨线程调用错误解析及解决办法
    SVN版本服务器搭建(服务端+客户端)
    opencv配置过程 (cmake,vs2013,qt 5.4)
    基数排序/Go实现
    c/c++ 编译器内存对齐问题
  • 原文地址:https://www.cnblogs.com/jakeasd/p/5537853.html
Copyright © 2011-2022 走看看