建立Bank类,类中有变量double balance表示存款,Bank类的构造方法能初始化余额,Bank类中有存款的方法cunKuan(double balance),取款的发方法withDrawal(double dAmount),当取款的数额大于存款时,抛出InsufficientFundsException,取款数额为负数,抛出NagativeFundsException,当用方法withdrawal(150),withdrawal(-15)时会抛出自定义异常。
1 public class Bank { 2 double yu_e; 3 double balance; 4 5 Bank(double yu_e) { 6 this.yu_e = yu_e; 7 System.out.println("账户内余额:"+this.yu_e+"元"); 8 } 9 10 void cunKuan(double balance) throws Exception { 11 if(balance<0){ 12 throw new Exception("存款不能为负"); 13 } 14 yu_e += balance; 15 } 16 17 void withDrawal(double dAmount) throws Exception { 18 if(dAmount>yu_e){ 19 throw new Exception("InsufficientFundsException,余额不足"); 20 }else if (dAmount<0){ 21 throw new Exception("NagativeFundsException,取款值为负"); 22 } 23 yu_e -= dAmount; 24 } 25 26 public static void main(String[] args) { 27 28 Bank b = new Bank(10); 29 try { 30 b.cunKuan(-100); 31 } catch (Exception e) { 32 e.printStackTrace(); 33 } 34 35 try { 36 b.withDrawal(150); 37 } catch (Exception e) { 38 e.printStackTrace(); 39 } 40 41 try { 42 b.withDrawal(-15); 43 } catch (Exception e) { 44 e.printStackTrace(); 45 } 46 47 System.out.println("存款余额"+b.yu_e+"元"); 48 49 } 50 51 }
运行: