บทนำ
Class Exception Implement Throwable Interface เป็น Base Class ของทุก Exception Classes (Predefined และ User-defined) Exception Class กำหนด Methods Final (Non-overridable) สำหรับ Throwable Interface และ __toString() ที่ Override ได้เพื่อ String Representation
Exception Methods
| Method | คำอธิบาย |
|---|---|
final public getMessage() | Error Message |
final public getCode() | Error Code |
final public getFile() | Source Filename |
final public getLine() | Source Line Number |
final public getTrace() | Backtrace Array |
final public getPrevious() | Previous Exception (Chaining) |
final public getTraceAsString() | Formatted Trace String |
public __toString() | Formatted String สำหรับแสดงผล (Override ได้) |
ถ้า User-defined Exception Override Constructor ต้องเรียก parent::__construct() เพื่อให้ Data ถูก Assign ครบ
ตัวอย่าง Custom Exception
Custom Exception myException โยนเมื่อ $num < 0 หรือ > 100:
<?php
class myException extends Exception {
function message() {
return "error: " . $this->getMessage() . " in line no " . $this->getLine();
}
}
$num = 125;
try {
if ($num > 100 || $num < 0) {
throw new myException("$num is invalid number");
} else {
echo "$num is a valid number";
}
} catch (myException $m) {
echo $m->message();
}
?>
ผลลัพธ์
error: 125 is invalid number in line no 10
ลอง $num = 90 จะได้ "90 is a valid number"
Custom Exception แบบสมบูรณ์
<?php
class ValidationException extends Exception {
private $field;
private $value;
public function __construct(string $message, string $field, $value, int $code = 0, Throwable $previous = null) {
$this->field = $field;
$this->value = $value;
parent::__construct($message, $code, $previous);
}
public function getField(): string {
return $this->field;
}
public function getValue() {
return $this->value;
}
public function __toString(): string {
return __CLASS__ . ": [{$this->code}]: {$this->message}\n in {$this->file}:{$this->line}\nField: {$this->field}, Value: " . var_export($this->value, true);
}
}
// Usage
try {
throw new ValidationException("Email invalid", "email", "not-an-email", 400);
} catch (ValidationException $e) {
echo $e->getField(); // "email"
echo $e->getValue(); // "not-an-email"
echo $e->getMessage(); // "Email invalid"
echo $e; // __toString() output
}
?>
Best Practices
- Extend
Exceptionสำหรับ Application Exceptions - Extend
RuntimeExceptionหรือLogicException(SPL) ตาม Semantics - Override
__toString()สำหรับ Debugging - เก็บ Context Data (Field, Value, etc.) ใน Properties
- ใช้ Exception Codes สำหรับ Categorization
- Constructor เรียก
parent::__construct()เสมอ
Exception Chaining
<?php
try {
// Low-level operation
} catch (PDOException $e) {
throw new RepositoryException("Database error", 0, $e); // Chain
}
?>