一道關(guān)于java異常處理的題目
1、建立exception包,編寫TestException.java程序,主方法中有以下代碼,確定其中可能出現(xiàn)的異常,進(jìn)行捕獲處理。
public class YiChang { public static void main(String[] args){ for(int i=0;i<4;i++){ int k; switch(i){ case 0: int zero=0; try{ k=911/zero; }catch(ArithmeticException e){ System.out.println("出現(xiàn)算數(shù)異常!"); } break; case 1: try{ int b[]=null; k = b[0]; }catch(NullPointerException e){ System.out.println("出現(xiàn)空指針異常!"); } break; case 2: int c[]=new int[2]; try{ k=c[9]; }catch(ArrayIndexOutOfBoundsException e){ System.out.println("出現(xiàn)數(shù)組序號(hào)溢出!"); } break; case 3: try{ char ch="abc".charAt(99); }catch(StringIndexOutOfBoundsException e){ System.out.println("出現(xiàn)數(shù)據(jù)類型轉(zhuǎn)換異常!"); } break; } } } }
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í)會(huì)拋出自定義異常。
public class InsufficientFundsException extends Exception { public String getMessage(){ return "您的余額不足!"; } } public class NagativeFundsException extends Exception{ public String getMessage(){ return "取款金額不能為負(fù)數(shù)!"; } } public class Bank { private static double balance; Bank(){ }; Bank(double balance){ this.balance=balance; } public static 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 b=new Bank(100); System.out.println("我有"+balance+"元存款!"); try{ withDrawal(150); }catch(InsufficientFundsException | NagativeFundsException e){ e.printStackTrace(); } try{ withDrawal(-15); }catch(NagativeFundsException |InsufficientFundsException e){ e.printStackTrace(); } } }
一道關(guān)于一道關(guān)于java異常處理的題目就給大家介紹這么多,希望對(duì)大家有所幫助,如果大家有任何疑問歡迎給我留言,小編會(huì)及時(shí)回復(fù)大家的,在此也非常感謝大家對(duì)腳本之家網(wǎng)站的支持!
相關(guān)文章
SpringBoot+Shiro+Redis+Mybatis-plus 實(shí)戰(zhàn)項(xiàng)目及問題小結(jié)
最近也是一直在保持學(xué)習(xí)課外拓展技術(shù),所以想自己做一個(gè)簡(jiǎn)單小項(xiàng)目,于是就有了這個(gè)快速上手 Shiro 和 Redis 的小項(xiàng)目,說白了就是拿來練手調(diào)調(diào) API,然后做完后拿來總結(jié)的小項(xiàng)目,感興趣的朋友一起看看吧2021-04-04Java實(shí)戰(zhàn)角色權(quán)限后臺(tái)腳手架系統(tǒng)的實(shí)現(xiàn)流程
只學(xué)書上的理論是遠(yuǎn)遠(yuǎn)不夠的,只有在實(shí)戰(zhàn)中才能獲得能力的提升,本篇文章手把手帶你用java+Springboot+Maven+myBaits-Plus+Vue+Element-UI+Mysql實(shí)現(xiàn)一個(gè)角色權(quán)限后臺(tái)腳手架系統(tǒng),大家可以在過程中查缺補(bǔ)漏,提升水平2022-01-01Java設(shè)計(jì)模式之Template?Pattern模板模式詳解
這篇文章主要介紹了Java設(shè)計(jì)模式之Template?Pattern模板模式詳解,模板模式(Template?Pattern)行為型模式之一,抽象父類定義一個(gè)操作中的算法的骨架,而將一些步驟延遲到子類中,需要的朋友可以參考下2023-10-10