例外処理 / ch02 — throw で例外を投げる / 演習 01
📝 ドリル 01 — 負の数で throw
問題
標準入力から整数を 1 行読み込みます。
n < 0ならthrow new Exception("負の数です")を投げる- それ以外なら
"OK: n = {n}"を 1 行出力する
try / catch で受け止め、catch ブロックでは "NG: 負の数です" を 1 行出力してください。
入力例 (tests/input.txt)
-3
期待される出力 (tests/expected.txt)
NG: 負の数です
採点
php scripts/grade.php v2/topics/10-exception/ch02-throw/drill/01-throw-on-negative/
ヒント
$n = (int) trim(fgets(STDIN));try { if ($n < 0) throw new Exception("負の数です"); else echo "OK: n = $n\n"; }catch (Exception $e) { echo "NG: " . $e->getMessage() . "\n"; }
テストケース
標準入力
-3
期待される出力
NG: 負の数です
📄 starter.php(雛形)
このコードから書き始めてください。
<?php
// TODO: 標準入力から整数 $n を読み込む
// $n = (int) trim(fgets(STDIN));
// TODO: try / catch を使う
// try の中で n < 0 なら throw new Exception("負の数です")
// それ以外は "OK: n = $n" を出力
// catch (Exception $e) の中で "NG: " . $e->getMessage() を出力
✅ 解答例を見る(自分で解いてから)
<?php
$n = (int) trim(fgets(STDIN));
try {
if ($n < 0) {
throw new Exception("負の数です");
}
echo "OK: n = $n\n";
} catch (Exception $e) {
echo "NG: " . $e->getMessage() . "\n";
}