PHP จับคำหลัก
ตัวอย่าง
จับข้อยกเว้น:
<?php
try {
throw new Exception("This is an exception");
}
catch(Exception $e) {
echo $e->getMessage();
}
?>
ความหมายและการใช้งาน
คีย์เวิร์ดใช้เพื่อจัดการกับ ข้อcatch
ยกเว้นที่เกิดจากโค้ดในกลุ่มtry ก่อน หน้า
หน้าที่เกี่ยวข้อง
throw
คีย์เวิร์ด.
try
คีย์เวิร์ด.
finally
คีย์เวิร์ด.
อ่านเพิ่มเติมเกี่ยวกับ try..catch.finally (ข้อยกเว้น) ใน บทช่วย สอนข้อยกเว้น PHPของ เรา
ตัวอย่างเพิ่มเติม
ตัวอย่าง
ใช้ catch สำหรับข้อยกเว้นหลายประเภท:
<?php
try {
$rand = rand(0, 2);
switch($rand) {
case 0: throw new Exception();
case 1: throw new
OutOfBoundsException();
case 2: throw new
LogicException();
}
} catch(OutOfBoundsException $e) {
echo "Caught an out of bounds exception";
} catch(LogicException $e) {
echo "Caught a logic exception";
} catch(Exception $e) {
echo
"Caught an ordinary exception";
}
?>
❮ คีย์เวิร์ด PHP