建立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 }
運行: