【轉】JDK1.8中的try-with-resources聲明

DK1.7開始,java引入了 try-with-resources 聲明,將 try-catch-finally 簡化爲 try-catch,這其實是一種語法糖,在編譯時會進行轉化爲 try-catch-finally 語句。新的聲明包含三部分:try-with-resources 聲明、try 塊、catch 塊。它要求在 try-with-resources 聲明中定義的變量實現了 AutoCloseable 接口,這樣在系統可以自動調用它們的close方法,從而替代了finally中關閉資源的功能。

但是,它們的異常拋出機制發生了變化。在過去的 try-catch-finally 結構中,我們在finally塊中關閉資源通常是這樣的:

    catch (Exception e) {
        e.printStackTrace(); // 第一處異常處理
    }
    finally {
        try {
            if (c != null) {
                c.close();
            }
        } catch (IOException e) {
            e.printStackTrace(); // 第二處異常處理
        }
    }
1
2
3
4
5
6
7
8
9
10
11
12
1
2
3
4
5
6
7
8
9
10
11
12
異常處理有兩種情況:

try 塊沒有發生異常時,直接調用finally塊,如果 close 發生異常,就處理。
try 塊發生異常,catch 塊捕捉,進行第一處異常處理,然後調用 finally 塊,如果 close 發生異常,就進行第二處異常處理。
但是在 try-with-resources 結構中,異常處理也有兩種情況(注意,不論 try 中是否有異常,都會首先自動執行 close 方法,然後才判斷是否進入 catch 塊,建議閱讀後面的反編譯代碼):

try 塊沒有發生異常時,自動調用 close 方法,如果發生異常,catch 塊捕捉並處理異常。
try 塊發生異常,然後自動調用 close 方法,如果 close 也發生異常,catch 塊只會捕捉 try 塊拋出的異常,close 方法的異常會在catch 中被壓制,但是你可以在catch塊中,用 Throwable.getSuppressed 方法來獲取到壓制異常的數組。
我們可以通過自定義的 AutoCloseable 類來理解這個過程。

public class Main {

    public static void startTest() {
        try (MyAutoCloseA a = new MyAutoCloseA();
             MyAutoCloseB b = new MyAutoCloseB()) {
            a.test();
            b.test();
        } catch (Exception e) {
            System.out.println("Main: exception");
            System.out.println(e.getMessage());
            Throwable[] suppressed = e.getSuppressed();
            for (int i = 0; i < suppressed.length; i++)
                System.out.println(suppressed[i].getMessage());
        }
    }

    public static void main(String[] args) throws Exception {
        startTest();
    }
}

/* 輸出爲:
    MyAutoCloaseA: test()
    MyAutoCloseB: on close
    MyAutoCloseA: on close()
    Main: exception
    MyAutoCloaseA: test() IOException
    MyAutoCloaseB: close() ClassNotFoundException
    MyAutoCloaseA: close() ClassNotFoundException
*/

class MyAutoCloseA implements AutoCloseable {

    public void test() throws IOException {
        System.out.println("MyAutoCloaseA: test()");
        throw new IOException("MyAutoCloaseA: test() IOException");
    }

    @Override
    public void close() throws Exception {
        System.out.println("MyAutoCloseA: on close()");
        throw new ClassNotFoundException("MyAutoCloaseA: close() ClassNotFoundException");
    }
}

class MyAutoCloseB implements AutoCloseable {

    public void test() throws IOException {
        System.out.println("MyAutoCloaseB: test()");
        throw new IOException("MyAutoCloaseB: test() IOException");
    }
    
    @Override
    public void close() throws Exception {
        System.out.println("MyAutoCloseB: on close");
        throw new ClassNotFoundException("MyAutoCloaseB: close() ClassNotFoundException");
    }
}
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
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
通過反編譯class文件,可以看到實際的執行過程:

    public static void startTest() {
       try {
           MyAutoCloseA a = new MyAutoCloseA();
           Throwable var33 = null;

           try {
               MyAutoCloseB b = new MyAutoCloseB();
               Throwable var3 = null;

               try { // 我們定義的 try 塊
                   a.test();
                   b.test();
               } catch (Throwable var28) { // try 塊中拋出的異常
                   var3 = var28;
                   throw var28;
               } finally {
                   if (b != null) {
                       // 如果 try 塊中拋出異常,就將 close 中的異常(如果有)附加爲壓制異常
                       if (var3 != null) {
                           try {
                               b.close();
                           } catch (Throwable var27) {
                               var3.addSuppressed(var27);
                           }
                       } else { // 如果 try 塊沒有拋出異常,就直接關閉,可能會拋出關閉異常
                           b.close();
                       }
                   }

               }
           } catch (Throwable var30) {
               var33 = var30;
               throw var30;
           } finally {
               if (a != null) {
                   if (var33 != null) {
                       try {
                           a.close();
                       } catch (Throwable var26) {
                           var33.addSuppressed(var26);
                       }
                   } else {
                       a.close();
                   }
               }

           }
       // 所有的異常在這裏交給 catch 塊處理
       } catch (Exception var32) { // 我們定義的 catch 塊
           System.out.println("Main: exception");
           System.out.println(var32.getMessage());
           Throwable[] suppressed = var32.getSuppressed();

           for(int i = 0; i < suppressed.length; ++i) {
               System.out.println(suppressed[i].getMessage());
           }
       }

   }
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
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
我還想補充的是:

catch 塊中,看不到 try-with-recourse 聲明中的變量。
try-with-recourse 中,try 塊中拋出的異常,在 e.getMessage() 可以獲得,而調用 close() 方法拋出的異常在e.getSuppressed() 獲得。
try-with-recourse 中定義多個變量時,由反編譯可知,關閉的順序是從後往前。
————————————————
版權聲明:本文爲CSDN博主「Harold Gao」的原創文章,遵循CC 4.0 BY-SA版權協議,轉載請附上原文出處鏈接及本聲明。
原文鏈接:https://blog.csdn.net/weixin_40255793/article/details/80812961

發佈了46 篇原創文章 · 獲贊 11 · 訪問量 5萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章