1、在java的構造方法中提供了 異常鏈.. 也就是我們可以通過構造方法不斷的將 異常串聯成一個異常鏈...
之所以需要異常連,是因為處于代碼的可理解性,以及閱讀和程序的可維護性...
我們知道我們每拋出一個異常都需要進行try catch ...那么豈不是代碼很臃腫...
我們如果可以將異常串聯成一個異常連,然后我們只捕獲我們的包裝 異常,我們知道 RuntimeException 以及其派生類可以不進行try catch 而被jvm自動捕獲并處理..
當然了我們可以自己定義自己的異常類從RuntimeException中派生,然后通過一級一級的包裝,假如異常出現了JWM通過我們的自定義RuntimeException直接輸出 cause
(原因)也就是 我們的異常鏈..因此我們的所有異常也就輸出了,這樣就減少了很多的異常處理的代碼。。。
只有 Throwable ----> Exception RuntimeException Error提供了 構造方法實現異常鏈的機制。。。其他異常需要通過initCause來
構造異常連..
下面一段代碼就是異常連的一個簡單示例...可以打印整個程序過程中出現的異常。。
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
|
public class TestT { public static void a() throws Exception{ //拋出異常給上級處理 try { b() ; } catch (Exception e) { throw new Exception(e) ; } } public static void b() throws Exception{ //拋出異常給上級處理 try { c() ; } catch (Exception e) { throw new Exception(e); } } public static void c() throws Exception { //拋出異常給上級處理 try { throw new NullPointerException( "c 異常鏈中的空指針異常.." ) ; } catch (NullPointerException e) { throw new Exception(e) ; } } public static void main(String[]args){ try { a() ; } catch (Exception e) { e.printStackTrace(); } } } |
2、 try catch ...finally 有個漏洞就是異常缺失.. 例如三個try catch 嵌套在一起 ..內部的2個try catch 就可以省略 catch ....直接 try finally ..
看下面代碼 我們發現丟失了2個異常信息
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
|
public class MyTest { public void open() throws Exception{ throw new Exception(){ public String toString() { return this .getClass().getName()+ "CeryImmportException" ; }; } ; } public void close() throws Exception{ throw new Exception(){ public String toString() { return this .getClass().getName()+ "close Exception" ; }; } ; } public void three() throws Exception{ throw new Exception(){ public String toString() { return this .getClass().getName() + "three" ; }; } ; } public static void main(String[]agrs){ MyTest mt= new MyTest() ; try { try { try { mt.open(); } finally { System.out.println( "delete open" ); mt.close() ; } } finally { System.out.println( "delete close" ); mt.three() ; } } catch (Exception ex){ ex.printStackTrace(); } } } |
以上這篇淺談java異常鏈與異常丟失就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持服務器之家。