PHP 8在异常方面有了新的变化。
1.新增内置异常类ValueError
在PHP 8版本之前,当传递值到函数时,如果是一个无效类型,则会导致警告。在PHP 8版本中,如果是无效类型,则会抛出异常ValueError。PHP 8新增的内置异常类ValueError继承自Exception基类。
例如,以下程序运行时将会抛出异常ValueError。
<?php
declare(strict_types=1);
/**
* 传递数组到array_rand,类型正确,但是array_rand期望传入的是非空数组
* 所以会抛出ValueError异常
*/
array_rand([], 0);
/**
* json_decode的深度参数必须是有效的正整型值,
* 所以这里也会抛出ValueError异常
*/
json_decode('{}', true, -1);
?>
2.throw表达式
在异常中,可以将throw用作表达式,例如:
$value = $nullableValue ?? throw new InvalidArgumentException();
3.捕获异常而不存储到变量
现在可以编写catch(Exception)代码块来捕获异常,而不将其存储在变量中。如果用不到异常信息,可以不设变量,从而减少内存消耗。
<?php
declare(strict_types=1);
$nullableValue = null;
try {
$value = $nullableValue ?? throw new \InvalidArgumentException();
} catch (\InvalidArgumentException) {
var_dump("发生过异常!");
}
exit;
?>