java 19 - 3 JDK7針對多個異常的處理方式


 1 /*
 2   JDK7出現了一個新的異常處理方案:
 3           try{
 4   
 5           }catch(異常名1 | 異常名2 | ...  變量 ) {
 6               ...
 7           }
 8    如果編譯期異常,又不知道異常名,就跟進看源碼,那里面就能找到
 9     注意:這個方法雖然簡潔,但是也不夠好。
10              A:處理方式是一致的。(實際開發中,好多時候可能就是針對同類型的問題,給出同一個處理)
11              B:多個異常間必須是平級關系。
12  */
13 public class ExceptionDemo3 {
14     public static void main(String[] args) {
15         method();
16     }
17 
18     public static void method() {
19         int a = 10;
20         int b = 0;
21         int[] arr = { 1, 2, 3 };
22 
23         // try {
24         // System.out.println(a / b);
25         // System.out.println(arr[3]);
26         // System.out.println("這里出現了一個異常,你不太清楚是誰,該怎么辦呢?");
27         // } catch (ArithmeticException e) {
28         // System.out.println("除數不能為0");
29         // } catch (ArrayIndexOutOfBoundsException e) {
30         // System.out.println("你訪問了不該的訪問的索引");
31         // } catch (Exception e) {
32         // System.out.println("出問題了");
33         // }
34 
35         // JDK7的處理方案
36         try {
37             System.out.println(a / b);
38             System.out.println(arr[3]);
39         } catch (ArithmeticException | ArrayIndexOutOfBoundsException e) {
40             System.out.println("出問題了");
41         }
42 
43         System.out.println("over");
44     }
45 
46 }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM