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

Exception Handling ด้วย Multiple Catch Blocks ใน PHP

บทนำ

PHP อนุญาตให้มีหลาย Catch Blocks ต่อ Try Block เพื่อจัดการ Exception Cases ต่างๆ Catch Blocks ต่างๆ อาจจัดการ Predefined Exceptions/Errors และ User-defined Exceptions

ตัวอย่าง Multiple Catch Blocks

จัดการ DivisionByZeroError, TypeError, ArgumentCountError, InvalidArgumentException และ General Exception:

<?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) {
    echo $x->getMessage();
}
catch (DivisionByZeroError $y) {
    echo $y->getMessage();
}
catch (ArgumentCountError $z) {
    echo $z->getMessage();
}
catch (InvalidArgumentException $i) {
    echo $i->getMessage();
}
catch (Exception $ex) {
    echo $ex->getMessage();
}
?>

ผลลัพธ์ต่างๆ ตามค่า Input

1. $b = 0 (Division by Zero)

Division by 0

2. $b = 3 (TypeError - Return Float แต่ Declared int)

Return value of divide() must be of the type integer, float returned

3. เรียก divide($a) เดียว (ArgumentCountError)

Too few arguments to function divide(), 1 passed ... exactly 2 expected

4. Argument ไม่ใช่ Integer (InvalidArgumentException)

Invalid type of arguments

ลำดับของ Catch Blocks สำคัญ

Catch Blocks ต้องเรียงจาก Specific ไป General (Subclass ก่อน Parent Class):

<?php
try {
    // code
} catch (SpecificException $e) {
    // จัดการ Specific
} catch (GeneralException $e) {
    // จัดการ General
} catch (Exception $e) {
    // จับ Exception ทุกชนิดที่เหลือ
}
?>

ถ้าวาง Exception ก่อน SpecificException จะไม่มีโอกาสรัน

Multi-catch (PHP 7.1+)

จับหลาย Exception Types ใน Catch เดียวได้ด้วย Pipe (|):

<?php
try {
    // code
} catch (TypeError | ArgumentCountError | DivisionByZeroError $e) {
    echo "Error: " . $e->getMessage();
} catch (Exception $e) {
    echo "Other: " . $e->getMessage();
}
?>

Best Practices

  • Catch Specific Exceptions ก่อน General
  • ใช้ Multi-catch สำหรับ Exception ที่จัดการเหมือนกัน
  • อย่า Catch Exception แล้วไม่ทำอะไร (Silent Fail)
  • Log Exception ก่อน Handle/Re-throw
  • ใช้ Finally สำหรับ Cleanup (Close DB, File Handles)