我正在為面向?qū)ο缶幊痰那锛究荚囎鰷?zhǔn)備,我們得到的一種任務(wù)是提供代碼的輸出,這些代碼通常包含一些異常處理問(wèn)題?,F(xiàn)在我的問(wèn)題是 try-with-resources 什么時(shí)候關(guān)閉它的資源,因?yàn)槲业妮敵鰢?yán)格依賴(lài)于實(shí)現(xiàn) AutoCloseable 的類(lèi)的輸出。在提供的代碼中,我不明白為什么“close 1”輸出出現(xiàn)在“close 40”之前,或者為什么對(duì)象 A(40) 在此塊末尾關(guān)閉。是因?yàn)?A(50) 與 A(40) 是同一類(lèi)型嗎?我的主要問(wèn)題是 AutoCloseable 何時(shí)關(guān)閉給定資源,例如示例 m1 當(dāng) i=1 時(shí):1) 創(chuàng)建 A(1) 1b) 執(zhí)行 Try 塊 2) 關(guān)閉 A(1) 3) 處理 ArrayIndexOutOfBoundsException?public class Main { public static void main(String[] args) { int[] arr = new int[] { 15, 10 }; for(int i=1; i>=-1; i--){ try(A a40 = new A(40)) { m1(arr, i); A a50 = new A(50); } catch(ArrayIndexOutOfBoundsException e) { System.out.println("array exc"); } catch(Exception e) { System.out.println("main exc"); break; } finally { System.out.println("main finally"); } } System.out.println("main done"); } private static void m1(int[] arr, int i) throws Exception { try(A a1 = new A(i)) { m2(arr[i] + arr[i+1], i); } catch(ArrayIndexOutOfBoundsException e) { System.out.println("m1 exc"); } System.out.println("m1 done"); } private static int m2(int x, int y) { int r = 0; try{ A a2 = new A(x+y); r = x / y; } finally { System.out.println("m2 finally"); } System.out.println("m2 done"); return r; }}以及實(shí)現(xiàn) AutoCloseable 的 A 類(lèi):public class A implements AutoCloseable { private int x; public A(int x){ this.x = x; System.out.println("A " + x); } @Override public void close() throws Exception { System.out.println("close " + x); }}這是提供的代碼的輸出:A 40A 1close 1m1 excm1 doneA 50close 40main finallyA 40A 0A 25m2 finallyclose 0close 40main excmain finallymain done
1 回答

MMMHUHU
TA貢獻(xiàn)1834條經(jīng)驗(yàn) 獲得超8個(gè)贊
規(guī)范對(duì)此非常清楚。
14.20.3。試用資源
try-with-resources 語(yǔ)句使用局部變量(稱(chēng)為資源)進(jìn)行參數(shù)化,這些局部變量在執(zhí)行 try 塊之前初始化,并在執(zhí)行try 塊之后以與初始化相反的順序自動(dòng)關(guān)閉。
你的例子有點(diǎn)復(fù)雜。嘗試簡(jiǎn)化它。您感興趣的場(chǎng)景有兩種:try 塊中引發(fā)異常,try 塊中未引發(fā)異常。您調(diào)試的消息會(huì)提供豐富的信息,因此您將能夠輕松跟蹤流程。
您可能想查看反編譯的 .classes 以了解實(shí)際生成的內(nèi)容。
添加回答
舉報(bào)
0/150
提交
取消