当前位置:  首页>> 技术小册>> PHP8入门与项目实战(5)

PHP 8在异常方面有了新的变化。

1.新增内置异常类ValueError

在PHP 8版本之前,当传递值到函数时,如果是一个无效类型,则会导致警告。在PHP 8版本中,如果是无效类型,则会抛出异常ValueError。PHP 8新增的内置异常类ValueError继承自Exception基类。

例如,以下程序运行时将会抛出异常ValueError。

  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * 传递数组到array_rand,类型正确,但是array_rand期望传入的是非空数组
  5. * 所以会抛出ValueError异常
  6. */
  7. array_rand([], 0);
  8. /**
  9. * json_decode的深度参数必须是有效的正整型值,
  10. * 所以这里也会抛出ValueError异常
  11. */
  12. json_decode('{}', true, -1);
  13. ?>

2.throw表达式
在异常中,可以将throw用作表达式,例如:

  1. $value = $nullableValue ?? throw new InvalidArgumentException();

3.捕获异常而不存储到变量
现在可以编写catch(Exception)代码块来捕获异常,而不将其存储在变量中。如果用不到异常信息,可以不设变量,从而减少内存消耗。

  1. <?php
  2. declare(strict_types=1);
  3. $nullableValue = null;
  4. try {
  5. $value = $nullableValue ?? throw new \InvalidArgumentException();
  6. } catch (\InvalidArgumentException) {
  7. var_dump("发生过异常!");
  8. }
  9. exit;
  10. ?>