一道關於java異常處理的題目_java

來源:互聯網
上載者:User

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("出現null 指標異常!");}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異常處理的題目就給大家介紹這麼多,希望對大家有所協助,如果大家有任何疑問歡迎給我留言,小編會及時回複大家的,在此也非常感謝大家對雲棲社區網站的支援!

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.