PHP 7 中的異常和錯誤
在早期版本的 PHP 中,我們只能處理異常。無法處理錯誤。在致命錯誤的情況下,它會停止整個應用程式或應用程式的某些部分。為了克服這個問題,PHP 7 添加了 Throwable 介面來處理異常和錯誤。
異常:在發生致命且可恢復的錯誤時,PHP 7 會丟擲異常,而不是停止整個應用程式或指令碼執行。
錯誤:PHP 7 丟擲 TypeError、ArithmeticError、ParserError 和 AssertionError,但警告和通知錯誤保持不變。使用 try/catch 塊可以捕獲錯誤例項,現在,致命錯誤可以丟擲錯誤例項。在 PHP 7 中,添加了一個 Throwable 介面來統一兩個異常分支,Exception 和 Error,以實現 Throwable。
示例
<?php class XYZ { public function Hello() { echo "class XYZ
"; } } 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
"; ?>
輸出
在上面的程式中,我們將得到以下錯誤:
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
注意:在上面的示例中,我們在空物件上呼叫了一個方法。catch 用於處理異常,然後繼續 PHP 程式碼。
算術錯誤
我們將使用算術錯誤的 DivisionByZeroError。但我們仍然會在除法運算子上得到警告錯誤。
示例:算術錯誤
<?php $x = 10; $y = 0; try { $z = intdiv($x , $y); } catch (DivisionByZeroError $e) { echo "Error has occured
"; echo $e->getMessage() . PHP_EOL ; echo "File: " . $e->getFile() . PHP_EOL; echo "Line: " . $e->getLine(). PHP_EOL; } echo "$z
"; echo " continues with the PHP code
"; ?>
輸出
上面程式的輸出將執行並顯示警告錯誤:
Division by zero File: /home/cg/root/9008538/main.php Line: 5 continues with the PHP code
注意:在上面的程式中,我們在 intdiv() 函式內部捕獲並報告 DivisionByZeroError。
廣告