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

Nested Exception ใน PHP

บทนำ

Try-Catch Blocks สามารถ Nest ได้หลายระดับ Exception จะถูกจัดการในลำดับย้อนกลับ (Innermost First)

ตัวอย่าง Nested Try-Catch

Inner Try Block ตรวจสอบ Non-numeric Outer Try Block โยน DivisionByZeroError:

<?php
class myException extends Exception {
    function message() {
        return "error: " . $this->getMessage() . " in line no " . $this->getLine();
    }
}

$x = 10;
$y = 0;

try {
    if (is_numeric($x) === FALSE || is_numeric($y) === FALSE) {
        throw new myException("Non numeric data");
    }
} catch (myException $m) {
    echo $m->message();
    return;
}

if ($y == 0) {
    throw new DivisionByZeroError("Division by 0");
}
echo $x / $y;

} catch (DivisionByZeroError $e) {
    echo $e->getMessage() . " in line no " . $e->getLine();
}
?>

ผลลัพธ์

Division by 0 in line no 19

ทดสอบค่า Non-numeric

เปลี่ยนตัวแปรใดตัวหนึ่งเป็น Non-numeric:

error: Non numeric data in line no 20

ถ้าทั้งคู่เป็นตัวเลข

จะแสดงผลการหาร

หลักการสำคัญ

  • Innermost Catch จะจับ Exception ก่อน
  • ถ้า Inner Catch ไม่จับ (หรือ Re-throw) Outer Catch จะจับต่อ
  • ใช้ throw $e; เพื่อ Re-throw Exception เดิม
  • throw new OtherException($message, 0, $e); สำหรับ Exception Chaining (Previous Exception)

Exception Chaining (PHP 7+)

<?php
try {
    try {
        throw new Exception("Original error");
    } catch (Exception $e) {
        throw new RuntimeException("Wrapped error", 0, $e);
    }
} catch (RuntimeException $e) {
    echo "Main: " . $e->getMessage() . "\n";
    echo "Previous: " . $e->getPrevious()->getMessage() . "\n";
}
?>

ผลลัพธ์

Main: Wrapped error
Previous: Original error