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

Exceptions และ Error ใน PHP 7

ใน PHP เวอร์ชันเก่า เราจัดการได้แค่ exceptions ไม่สามารถจัดการ errors ได้ ในกรณีของ Fatal Error มันจะหยุดแอปพลิเคชันทั้งหมดหรือบางส่วน เพื่อแก้ปัญหานี้ PHP 7 เพิ่ม throwable interface เพื่อจัดการทั้ง exceptions และ errors

Exception: ทุกครั้งที่เกิด fatal และ recoverable error PHP 7 จะโยน exception แทนการหยุดแอปพลิเคชันหรือการทำงานของสคริปต์ทั้งหมด

Error: PHP 7 โยน TypeError, ArithmeticError, ParserError, และ AssertionError แต่ warning และ notice errors ยังคงไม่เปลี่ยนแปลง โดยใช้ try/catch block error instance สามารถจับได้ และตอนนี้ FatalErrors สามารถโยน error instance ได้ ใน PHP 7 throwable interface ถูกเพิ่มเพื่อรวมสองสาขาข้อยกเว้น Exception และ Error เพื่อ implement throwable

ตัวอย่าง

<?php 
    class XYZ { 
        public function Hello() { 
            echo "class XYZ\n"; 
        } 
    } 
    try { 
        $a = new XYZ(); 
        $a->Hello(); 
        $a = null; 
        $a->Hello(); 
    } 
    catch (Error $e) { 
        echo "Error occurred". PHP_EOL; 
        echo $e->getMessage() . PHP_EOL ; 
        echo "File: " . $e->getFile() . PHP_EOL; 
        echo "Line: " . $e->getLine(). PHP_EOL; 
    } 
    echo "Continue the PHP code\n"; 
?>

ผลลัพธ์

ในโปรแกรมด้านบน เราจะได้ข้อผิดพลาดดังนี้ -

class XYZ Error occurred Call to a member function Hello() on null File: /home/cg/root/9008538/main.php Line: 11 Continue with the PHP code

หมายเหตุ: ในตัวอย่างด้านบน เราเรียกเมธอดบนอ็อบเจกต์ null catch ใช้จัดการข้อยกเว้นและต่อโค้ด PHP ต่อไป

Arithmetic Error

เราจะใช้ DivisionByZeroError ของ arithmetic error แต่ยังคงได้ warning error บนตัวดำเนินการหาร

ตัวอย่าง: arithmetic error

<?php 
    $x = 10; 
    $y = 0; 
    try { 
        $z = intdiv($x , $y); 
    } 
    catch (DivisionByZeroError $e) { 
        echo "Error has occured\n"; 
        echo $e->getMessage() . PHP_EOL ; 
        echo "File: " . $e->getFile() . PHP_EOL; 
        echo "Line: " . $e->getLine(). PHP_EOL; 
    } 
    echo "$z \n"; 
    echo " continues with the PHP code\n"; 
?>

ผลลัพธ์

ผลลัพธ์สำหรับโปรแกรมด้านบนจะ execute พร้อม warning error -

Division by zero File: /home/cg/root/9008538/main.php Line: 5 continues with the PHP code

หมายเหตุ: ในโปรแกรมด้านบน เราจับและรายงาน DivisionByZeroError ภายในฟังก์ชัน intdiv()