Java-异常处理练习
生活随笔
收集整理的這篇文章主要介紹了
Java-异常处理练习
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
1.建立exception包,編寫TestException.java程序,主方法中有以下代碼,確定其中可能出現(xiàn)的異常,進(jìn)行捕獲處理。
package Yichang;public class Text {public static void main(String[] args) {for(int i=0;i<4;i++){int k;switch(i){case 0:try{int zero=0;k=911/zero;}catch(ArithmeticException e){System.out.println("輸入有誤");}break;case 1:try{int b[]=null;k = b[0];}catch(NullPointerException e){System.out.println("空指針異常");}break;case 2:try{int c[]=new int[2];k=c[9];}catch(ArrayIndexOutOfBoundsException e){System.out.println("索引超出異常");}break;case 3:try{char ch="abc".charAt(99);}catch(Exception e){e.printStackTrace();System.out.println("收取字符超出");}break;}}}}結(jié)果:
2.建立exception包,建立Bank類,類中有變量double ?balance表示存款,Bank類的構(gòu)造方法能增加存款,Bank類中有取款的發(fā)方法withDrawal(double dAmount),當(dāng)取款的數(shù)額大于存款時(shí),拋出InsufficientFundsException,取款數(shù)額為負(fù)數(shù),拋出NagativeFundsException,如new Bank(100),表示存入銀行100元,當(dāng)用方法withdrawal(150),withdrawal(-15)時(shí)會拋出自定義異常。
?
package Yichang;public class InsufficientFundsException extends Exception {public String getMessage(){return "余額不足";} } package Yichang;public class NagativeFundsException extends Exception {public String getMessage(){return "取款不能為負(fù)數(shù)";} } package Yichang;public class Test01 {private double balance;public Test01(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){Test01 t=new Test01(100);try{t.withDrawal(150);}catch(Exception e){e.printStackTrace();}try{t.withDrawal(-10);}catch(Exception e){e.printStackTrace();}} }結(jié)果:
?
轉(zhuǎn)載于:https://www.cnblogs.com/gzhnan/articles/9752332.html
總結(jié)
以上是生活随笔為你收集整理的Java-异常处理练习的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: gitlab的搭建与汉化
- 下一篇: ActiveMQ_3Java实现