From 9d88fdc769db1b0e1fedbbd869927260608a216e Mon Sep 17 00:00:00 2001 From: m-takatsuki <26-m-takatsuki-webstar@it-college.co.jp> Date: Wed, 21 Oct 2026 16:40:25 +0900 Subject: [PATCH] =?UTF-8?q?Ex.01=20=E5=AE=8C=E4=BA=86?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Question16-Exception/Ex01.php | 36 +++++++++++++++++++++++++++++++++++ 1 file changed, 36 insertions(+) diff --git a/Question16-Exception/Ex01.php b/Question16-Exception/Ex01.php index b8a15ac..faf82c4 100644 --- a/Question16-Exception/Ex01.php +++ b/Question16-Exception/Ex01.php @@ -14,3 +14,39 @@ * * */ + +// 関数 divide($numerator, $denominator) を作成 +function divide($numerator, $denominator) +{ + + // $denominator が 0 の場合、Exception を投げる。 + + if ($denominator === 0) { + throw new Exception("0で割ることはできません"); + } + + // - 正常な場合は、$numerator / $denominator の結果を返す。 + else { + return $numerator / $denominator; + } +} +// GETリクエストで分子(num)と分母(den)の値を受け取り、 +$numerator = $_GET['num']; +$denominator = $_GET['den']; + + +// 例外が発生した場合は try-catch ブロックで捕捉し、「Error: {エラーメッセージ}」と出力すること。 + +echo "処理開始" . "
"; +try { + if ($numerator / $denominator === "") { + throw new Exception("結果を受け取れません"); + } + + // 結果でdivide() を呼び出す + $result = divide($numerator, $denominator); + + echo "結果は{$result}"; +} catch (Exception $e) { + echo "Error:" . $e->getMessage(); +}