Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> PHP

การโยน Exception (Throwing Exceptions) ใน PHP

บทนำ

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คำอธิบาย
LogicExceptionError ใน Program Logic
BadFunctionCallExceptionCallback อ้างฟังก์ชันที่ไม่มีอยู่ หรือ Missing Arguments
BadMethodCallExceptionCallback อ้างเมธอดที่ไม่มีอยู่ หรือ Missing Arguments
DomainExceptionValue ไม่สอดคล้องกับ Valid Data Domain
InvalidArgumentExceptionArgument Type ไม่ตรงที่คาดหวัง
LengthExceptionLength ไม่ถูกต้อง
OutOfRangeExceptionRequest Index ผิดกฎหมาย
RuntimeExceptionError ที่พบได้เฉพาะ Runtime
OutOfBoundsExceptionValue ไม่ใช่ Valid Key
OverflowExceptionเพิ่ม Element เข้า Container ที่เต็มแล้ว
RangeExceptionRange Errors ระหว่าง Execution
UnderflowExceptionOperation ผิดกฎบน Empty Container
UnexpectedValueExceptionValue ไม่ตรงกับ 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