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。

更新于: 2021年3月13日

505 次查看

开启你的 职业生涯

通过完成课程获得认证

开始学习
广告

© . All rights reserved.