ข้อยกเว้นคือปัญหาที่เกิดขึ้นระหว่างการทำงานของโปรแกรม ในระหว่างการดำเนินการของโปรแกรมเมื่อมีข้อยกเว้นเกิดขึ้น โค้ดที่ตามหลังคำสั่งจะไม่ถูกดำเนินการ และ PHP จะพยายามค้นหาบล็อก catch ที่ตรงกันตัวแรก หากไม่พบข้อยกเว้น PHP Fatal Error จะออกมาพร้อมกับ “Uncaught Exception”
ไวยากรณ์
try {
print "this is our try block";
throw new Exception();
}catch (Exception $e) {
print "something went wrong, caught yah! n";
}finally {
print "this part is always executed";
} ตัวอย่าง
<?php
function printdata($data) {
try {
//If var is six then only if will be executed
if($data == 6) {
// If var is zero then only exception is thrown
throw new Exception('Number is six.');
echo "\n After throw (It will never be executed)";
}
}
// When Exception has been thrown by try block
catch(Exception $e){
echo "\n Exception Caught", $e->getMessage();
}
//this block code will always executed.
finally{
echo "\n Final block will be always executed";
}
}
// Exception will not be rised here
printdata(0);
// Exception will be rised
printdata(6);
?> ผลลัพธ์
Final block will be always executed Exception CaughtNumber is six. Final block will be always executed
หมายเหตุ
เพื่อจัดการกับข้อยกเว้น รหัสโปรแกรมต้องอยู่ภายในบล็อกการลอง การลองแต่ละครั้งต้องมีบล็อก catch อย่างน้อยหนึ่งบล็อก สามารถใช้ catch block หลายอันเพื่อตรวจจับคลาสของข้อยกเว้นต่างๆ ได้