対策する資格
Java Silver ・ 近日ORACLE Silver ・ 近日
Gold 保有者 監修1Z0-829 対応
try-with-resources / 抑制例外難易度 高無料

次のコードの出力として正しいものを選べ。

 1  public class Q10 {
 2      static class Res implements AutoCloseable {
 3          public void close() { throw new RuntimeException("close-fail"); }
 4      }
 5      public static void main(String[] args) {
 6          try (Res r = new Res()) {
 7              throw new RuntimeException("body-fail");
 8          } catch (Exception e) {
 9              System.out.println(e.getMessage());
10              for (Throwable t : e.getSuppressed())
11                  System.out.println("suppressed: " + t.getMessage());
12          }
13      }
14  }
  1. Aclose-fail 改行 suppressed: body-fail
  2. Bbody-fail 改行 suppressed: close-fail
  3. Cbody-fail のみ
  4. Dclose-fail のみ
正解・解説・誤答理由・ひっかけを見る▼ open
✓ 正解:BGold監修

解説

try-with-resources で本体(try ブロック)の例外と close() の例外が両方発生した場合、 本体の例外が主(プライマリ)として伝播し、close() 側の例外は抑制例外(suppressed)として 主例外に addSuppressed で付加される(JLS §14.20.3)。 よって catch が捕捉する e"body-fail"getMessage())、 e.getSuppressed() には "close-fail" が入る。
各誤答が違う理由
  • A主と抑制が逆。本体の例外が主、close の例外が抑制される(close が主ではない)。
  • Cclose の例外は握り潰されず getSuppressed() で取得できる。出力に suppressed: close-fail が現れる。
  • Dclose の例外が主として捕捉されるとした誤り。捕捉されるのは本体の body-fail
ひっかけ: 「最後に投げられた close の例外が勝つ」と思いがち。実際は本体例外が主、close例外が抑制
実機確認の答え合わせ
出力:
body-fail
suppressed: close-fail
Gold 保有者による書き下ろし解説・実機で検証済
この分野をもっと解いて、得点源に
try-with-resources を含む全問を分野別に演習できます(無料)。
演習する →