例外処理 / ch04 — 複数の catch ブロック / 演習 01
📝 ドリル 01 — 2 種類の例外を別 catch で受ける
問題
try の中で次のように書いてください。
throw new RuntimeException("実行時の問題")を投げる
catch を 2 つ並べてください。
catch (InvalidArgumentException $e)で"引数: " . $e->getMessage()を出力catch (RuntimeException $e)で"実行時: " . $e->getMessage()を出力
期待される出力:
実行時: 実行時の問題
採点
php scripts/grade.php v2/topics/10-exception/ch04-multi-catch/drill/01-two-types/
ヒント
- catch を上から並べる順番は自由だが、投げる型に対応する catch だけが走る
RuntimeExceptionは PHP 標準の例外クラス
テストケース
期待される出力
実行時: 実行時の問題
📄 starter.php(雛形)
このコードから書き始めてください。
<?php
// TODO: try { throw new RuntimeException("実行時の問題"); }
// TODO: catch (InvalidArgumentException $e) { "引数: " . $e->getMessage() を出力 }
// TODO: catch (RuntimeException $e) { "実行時: " . $e->getMessage() を出力 }
✅ 解答例を見る(自分で解いてから)
<?php
try {
throw new RuntimeException("実行時の問題");
} catch (InvalidArgumentException $e) {
echo "引数: " . $e->getMessage() . "\n";
} catch (RuntimeException $e) {
echo "実行時: " . $e->getMessage() . "\n";
}