我正在為面向對象編程的秋季考試做準備,我們得到的一種任務是提供代碼的輸出,這些代碼通常包含一些異常處理問題?,F在我的問題是 try-with-resources 什么時候關閉它的資源,因為我的輸出嚴格依賴于實現 AutoCloseable 的類的輸出。在提供的代碼中,我不明白為什么“close 1”輸出出現在“close 40”之前,或者為什么對象 A(40) 在此塊末尾關閉。是因為 A(50) 與 A(40) 是同一類型嗎?我的主要問題是 AutoCloseable 何時關閉給定資源,例如示例 m1 當 i=1 時:1) 創建 A(1) 1b) 執行 Try 塊 2) 關閉 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; }}以及實現 AutoCloseable 的 A 類: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貢獻1834條經驗 獲得超8個贊
規范對此非常清楚。
14.20.3。試用資源
try-with-resources 語句使用局部變量(稱為資源)進行參數化,這些局部變量在執行 try 塊之前初始化,并在執行try 塊之后以與初始化相反的順序自動關閉。
你的例子有點復雜。嘗試簡化它。您感興趣的場景有兩種:try 塊中引發異常,try 塊中未引發異常。您調試的消息會提供豐富的信息,因此您將能夠輕松跟蹤流程。
您可能想查看反編譯的 .classes 以了解實際生成的內容。
添加回答
舉報
0/150
提交
取消