異常的使用實例(異常分類:Error(是由JVM調用系統底層發生的,只能修改代碼) 和 Exception(是JVM發生的,可以進行針對性處理))
1.如果一個方法內可能出現異常,那么可以將異常通過throw的方式new 出相應的異常類,并在方法上 聲明throws可能拋出的異常類拋給調用者,調用者可以進行異常捕獲,或者繼續拋出異常由 上層調用者繼續處理, 如果整個過程都沒有將異常進行任何處理,那么將由JVM虛擬機進行默認的處理
2.調用者可以對異常進行try()catch(){}的異常處理, 也可以繼續在方法后面throws該異常,catch代碼塊中 如果不處理也可以進行throw該異常
3.運行時異常RuntimeException可以不進行顯式的異常聲明
4.如果父類中的方法拋出了異常,如果子類對方法進行重寫后也拋出異常,那么該異常必須不能大于父類的異常類, 如果父類中方法沒有拋出異常,而子類中覆蓋的方法卻拋出了異常,那么此時只能進行try catch來捕獲此異常,但是也可以將此異常在catch代碼塊中throw new RuntimeExcetion()進行拋出,這樣方法不用進行throws聲明
5.很多時候異常并不需要調用者進行處理,調用者不一定具有處理能力
6.異常應該包裝成上層調用者可以識別的異常類型,面向不同的調用者,報告不同的異常信息,否者調用者不知道如何處理該異常
在開發中這點十分重要
7.finally代碼塊中常常進行資源的釋放及關閉操作,對于打開的資源應該進行反方向的關閉操作,因為資源可能存在依賴性
8.如果不進行聲明異常,那么目的是不讓調用者進行處理,讓調用者的程序停止,這樣必須修改錯誤代碼
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
|
public class ExceptionDemo { public static void main(String[] args) { //OutOfMemoryError內存溢出錯誤, int[] i = new int[1024*1024*1024]; System.out.println(i[1]); //ArrayIndexOutOfBoundsException索引越界異常 int[] s = new int[2]; System.out.println(s[2]); Calc calc = new Calc(); //假如我們在這里捕獲異常 try { calc.run(4, 0); calc.run(4, -1); } catch (NegativeException e) {//必須先拋出異常的自定義子類 e.printStackTrace(); System.out.println(e.getMessage()); //throw e;//可以繼續將此異常拋出 } catch (ArithmeticException e){//拋出自定義異常類的父類 e.printStackTrace(); System.out.println(e.getMessage()); //throw e; } finally { System.out.println("finally肯定會執行到"); } //如果上面進行了異常捕獲,那么代碼可以繼續執行,否者代碼不能繼續執行 System.out.println("可以執行到!"); try { calc.run(4, -1); } catch (NegativeException e) { e.printStackTrace(); System.out.println(e.getMessage()); return; } finally { System.out.println("肯定會執行的"); } System.out.println("執行不到了");//執行不到此行代碼 } } /** * 自定義異常 */ class NegativeException extends ArithmeticException{ public NegativeException() { } public NegativeException(String msg) { super(msg); } } interface AA{ public abstract void method(); } class Calc implements AA{ //ArithmeticException其實為運行時異常(RuntimeException),即使不進行throws聲明,也可以通過編譯 public int run(int m,int n)throws ArithmeticException,NegativeException{ if(n==0){ throw new ArithmeticException("除數不能為0"); }else if(n<0){ throw new NegativeException("除數不能為負數"); } int s = m/n; return s ; } @Override public void method() { try { int p = 4/0; } catch (ArithmeticException e) { e.printStackTrace(); throw new RuntimeException();//將異常繼續拋出為運行時異常 } } } |
感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!