close の順番
出力はどれか。
public class Main {
public static void main(String[] args) {
try (Res a = new Res("A"); Res b = new Res("B")) {
System.out.print("body ");
}
}
}
class Res implements AutoCloseable {
private final String name;
Res(String name) { this.name = name; }
public void close() { System.out.print("close" + name + " "); }
}
- A
body closeB closeA - B
body closeA closeB - C
closeA closeB body - D コンパイルエラーになる
正解と解説を見る
正解: A
- A: リソースは try の本体の後に、宣言と逆の順 (B → A) で close されます。
- B: close は宣言と逆の順に呼ばれるので、A より B が先です。
- C: close は try の本体 (body) が終わった後に呼ばれます。
- D: Res は AutoCloseable を実装しているので、try-with-resources で使えます。
ポイント
- try-with-resources で宣言したリソースは、ブロックを抜けるときに自動で close されます。
- close は 宣言と逆の順番 です。
「try-with-resources 文による例外処理」をこのサイトで解く (記録・間違えた問題の解き直し・AI教師への質問)