แนะนำตัว
PHP อนุญาตให้มีชุดบล็อก catch ที่ติดตามบล็อก try เพื่อจัดการกับกรณียกเว้นต่างๆ อาจมีการใช้ catch block ต่างๆ เพื่อจัดการกับข้อยกเว้นและข้อผิดพลาดที่กำหนดไว้ล่วงหน้า เช่นเดียวกับข้อยกเว้นที่ผู้ใช้กำหนด
ตัวอย่าง
ตัวอย่างต่อไปนี้ใช้บล็อก catch เพื่อประมวลผลเงื่อนไข DivisioByZeroError, TypeError, ArgumentCountError และ InvalidArgumentException นอกจากนี้ยังมี catch block เพื่อจัดการข้อยกเว้นทั่วไป
ตัวอย่าง
<?php
declare(strict_types=1);
function divide(int $a, int $b) : int {
return $a / $b;
}
$a=10;
$b=0;
try{
if (!$b) {
throw new DivisionByZeroError('Division by zero.');}
if (is_int($a)==FALSE || is_int($b)==FALSE)
throw new InvalidArgumentException("Invalid type of arguments");
$result=divide($a, $b);
echo $result;
}
catch (TypeError $x)//if argument types not matching{
echo $x->getMessage();
}
catch (DivisionByZeroError $y) //if denominator is 0{
echo $y->getMessage();
}
catch (ArgumentCountError $z) //if no.of arguments not equal to 2{
echo $z->getMessage();
}
catch (InvalidArgumentException $i) //if argument types not matching{
echo $i->getMessage();
}
catch (Exception $ex) // any uncaught exception{
echo $ex->getMessage();
}
?> ผลลัพธ์
ในการเริ่มต้น เนื่องจากตัวส่วนเป็น 0, ข้อผิดพลาดหารด้วย 0 จะปรากฏขึ้น
Division by 0
ตั้งค่า $b=3 ซึ่งจะทำให้ TypeError เนื่องจากฟังก์ชันการหารคาดว่าจะคืนค่าจำนวนเต็ม แต่ผลการหารเป็นแบบลอย
Return value of divide() must be of the type integer, float returned
หากมีการส่งผ่านตัวแปรเพียงตัวเดียวเพื่อแบ่งฟังก์ชันโดยเปลี่ยน $res=divide($a); ซึ่งจะส่งผลให้ ArgumentCountError
Too few arguments to function divide(), 1 passed in C:\xampp\php\test1.php on line 13 and exactly 2 expected
หากอาร์กิวเมนต์ตัวใดตัวหนึ่งไม่ใช่จำนวนเต็ม จะเป็นกรณีของ InvalidArgumentException
Invalid type of arguments