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異常處理的題目就給大家介紹這么多,希望對大家有所幫助,如果大家有任何疑問歡迎給我留言,小編會及時回復大家的,在此也非常感謝大家對武林網網站的支持!
新聞熱點
疑難解答