PHP 7 中的异常和错误

phpserver side programmingprogramming

在 PHP 的早期版本中,我们只能处理异常。无法处理错误。在发生致命错误的情况下,它过去常常会停止整个应用程序或应用程序的某些部分。为了解决这个问题,PHP 7 添加了 throwable 接口来处理异常和错误。

异常: 无论何时发生致命和可恢复的错误,PHP 7 都会抛出异常,而不是停止整个应用程序或脚本执行。

错误:PHP 7 会抛出 TypeError、ArithmeticError、ParserError 和 AssertionError,但警告和通知错误保持不变。使用 try/catch 块,可以捕获错误实例,现在,FatalErrors 可以抛出错误实例。在 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 " 继续执行 PHP 代码
"; ?>

输出

上述程序的输出将执行并显示警告错误 −

Division by zero
File: /home/cg/root/9008538/main.php
Line: 5
继续执行 PHP 代码

注意:在上面的程序中,我们捕获并报告了 intdiv() 函数内的 DivisionByZeroError。


相关文章