一道關於java異常處置的標題。本站提示廣大學習愛好者:(一道關於java異常處置的標題)文章只能為提供參考,不一定能成為您想要的結果。以下是一道關於java異常處置的標題正文
1、樹立exception包,編寫TestException.java法式,主辦法中有以下代碼,肯定個中能夠湧現的異常,停止捕捉處置。
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("湧現算數異常!"); } break; case 1: try{ int b[]=null; k = b[0]; }catch(NullPointerException e){ System.out.println("湧現空指針異常!"); } break; case 2: int c[]=new int[2]; try{ k=c[9]; }catch(ArrayIndexOutOfBoundsException e){ System.out.println("湧現數組序號溢出!"); } break; case 3: try{ char ch="abc".charAt(99); }catch(StringIndexOutOfBoundsException e){ System.out.println("湧現數據類型轉換異常!"); } break; } } } }
2、樹立exception包,樹立Bank類,類中有變量double balance表現存款,Bank類的結構辦法能增長存款,Bank類中有取款的發辦法withDrawal(double dAmount),當取款的數額年夜於存款時,拋出InsufficientFundsException,取款數額為正數,拋出NagativeFundsException,如new Bank(100),表現存入銀行100元,當用辦法withdrawal(150),withdrawal(-15)時會拋出自界說異常。
public class InsufficientFundsException extends Exception { public String getMessage(){ return "您的余額缺乏!"; } } public class NagativeFundsException extends Exception{ public String getMessage(){ return "取款金額不克不及為正數!"; } } 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(); } } }
一道關於一道關於java異常處置的標題就給年夜家引見這麼多,願望對年夜家有所贊助,假如年夜家有任何疑問迎接給我留言,小編會實時答復年夜家的,在此也異常感激年夜家對網站的支撐!