close と catch・finally の順番
出力はどれか。
public class Main {
public static void main(String[] args) {
try (Res r = new Res()) {
System.out.print("try ");
throw new IllegalStateException();
} catch (IllegalStateException e) {
System.out.print("catch ");
} finally {
System.out.print("finally");
}
}
}
class Res implements AutoCloseable {
public void close() { System.out.print("close "); }
}
- A
try close catch finally - B
try catch close finally - C
try catch finally close - D コンパイルエラーになる
正解と解説を見る
正解: A
- A: try-with-resources では、catch や finally より前にリソースが close されます。
- B: close は catch より前に実行されます。
- C: close は finally より前、catch よりも前に実行されます。
- D: try-with-resources にも catch と finally を付けられるので、コンパイルできます。
ポイント
- リソースは、catch や finally より 先に close されます。
「try-with-resources 文による例外処理」をこのサイトで解く (記録・間違えた問題の解き直し・AI教師への質問)