บทนำ
Interface Throwable ถูก Implement โดย Class Error และ Exception Predefined Error Classes ทั้งหมดสืบทอดจาก Error Class Instance ของ Error Class ที่ตรงกันจะถูก Throw ใน Try Block และจัดการใน Catch Block ที่เหมาะสม
Throwing Exception
การทำงานปกติ (ไม่มี Exception ใน Try Block) จะดำเนินต่อหลัง Catch Block ตัวสุดท้าย
ตัวอย่าง: Division by Zero
<?php
function div($x, $y) {
if (!$y) {
throw new Exception('Division by zero.');
}
return $x / $y;
}
try {
echo div(10, 5) . "\n";
echo div(10, 0) . "\n";
} catch (Exception $e) {
echo 'Caught exception: ', $e->getMessage(), "\n";
}
// Continue execution
echo "Execution continues\n";
?>
ผลลัพธ์
2 Caught exception: Division by zero. Execution continues
ตัวอย่าง: TypeError
TypeError ถูก Throw เมื่อ Argument Type ไม่ตรง:
<?php
function add(int $num1, int $num2) {
return $num1 + $num2;
}
try {
$value = add(1, 'one'); // String แทน Integer
} catch (TypeError $e) {
echo $e->getMessage() . "\n";
}
?>
ผลลัพธ์
Argument 2 passed to add() must be of the type integer, string given
SPL Exceptions (Standard PHP Library)
PHP มี Predefined Exceptions ใน SPL:
| Exception | คำอธิบาย |
|---|---|
| LogicException | Error ใน Program Logic |
| BadFunctionCallException | Callback อ้างฟังก์ชันที่ไม่มีอยู่ หรือ Missing Arguments |
| BadMethodCallException | Callback อ้างเมธอดที่ไม่มีอยู่ หรือ Missing Arguments |
| DomainException | Value ไม่สอดคล้องกับ Valid Data Domain |
| InvalidArgumentException | Argument Type ไม่ตรงที่คาดหวัง |
| LengthException | Length ไม่ถูกต้อง |
| OutOfRangeException | Request Index ผิดกฎหมาย |
| RuntimeException | Error ที่พบได้เฉพาะ Runtime |
| OutOfBoundsException | Value ไม่ใช่ Valid Key |
| OverflowException | เพิ่ม Element เข้า Container ที่เต็มแล้ว |
| RangeException | Range Errors ระหว่าง Execution |
| UnderflowException | Operation ผิดกฎบน Empty Container |
| UnexpectedValueException | Value ไม่ตรงกับ Set ของ Values |
ตัวอย่าง: OutOfBoundsException
<?php
$arr = ["one" => 1, "two" => 2, "three" => 3, "four" => 4];
$key = "ten";
try {
if (array_key_exists($key, $arr) === FALSE) {
throw new OutOfBoundsException("key not found");
} else {
echo $arr[$key];
}
} catch (OutOfBoundsException $e) {
echo $e->getMessage() . "\n";
}
?>
ผลลัพธ์
key not found
Exception Hierarchy
Throwable
├── Error
│ ├── ArithmeticError
│ ├── AssertionError
│ ├── CompileError
│ ├── TypeError
│ └── ...
└── Exception
├── LogicException
│ ├── BadFunctionCallException
│ ├── BadMethodCallException
│ ├── DomainException
│ ├── InvalidArgumentException
│ ├── LengthException
│ └── OutOfRangeException
└── RuntimeException
├── OutOfBoundsException
├── OverflowException
├── RangeException
├── UnderflowException
└── UnexpectedValueException