PHP 7 错误处理

PHP 7 改变了大多数错误的报告方式。不同于传统(PHP 5)的错误报告机制,现在大多数错误被作为 Error 异常抛出。

这种 Error 异常可以像 Exception 异常一样被第一个匹配的 try / catch 块所捕获。如果没有匹配的 catch 块,则调用异常处理函数(事先通过 set_exception_handler() 注册)进行处理。 如果尚未注册异常处理函数,则按照传统方式处理:被报告为一个致命错误(Fatal Error)。

Error 类并非继承自 Exception 类,所以不能用 catch (Exception $e) { ... } 来捕获 Error。你可以用 catch (Error $e) { ... },或者通过注册异常处理函数( set_exception_handler())来捕获 Error

Error 层次结构

  • Throwable
    • Error
      • ArithmeticError
        • DivisionByZeroError
      • AssertionError
      • CompileError
        • ParseError
      • TypeError
        • ArgumentCountError
    • Exception
      • ...

User Contributed Notes

diogoca at gmail dot com 24-Nov-2019 02:38
<?php

set_error_handler
(function(int $number, string $message) {
   echo
"Handler captured error $number: '$message'" . PHP_EOL  ;
});

try {
    echo
$x; # notice, handled on callable
   
pg_exec(null, null); # warning, handled on callable
   
fho(); # fatal error, stop running and catched
} catch (Throwable $e) {
    echo
"Captured Throwable: " . $e->getMessage() . PHP_EOL;
}

?>

set_error_handler will also works without try and catch
ryan dot jentzsch@{gmail} dot com 08-Aug-2017 09:41
An excellent blog post on the difference between exceptions, throwables and how PHP 7 handles these can be found here: https://trowski.com/2015/06/24/throwable-exceptions-and-errors-in-php7/
lubaev dot ka at gmail dot com 01-Dec-2016 05:16
php 7.1

try {
   // Code that may throw an Exception or ArithmeticError.
} catch (ArithmeticError | Exception $e) {
   // pass
}
demis dot palma at tiscali dot it 26-Jul-2016 11:04
Throwable does not work on PHP 5.x.

To catch both exceptions and errors in PHP 5.x and 7, add a catch block for Exception AFTER catching Throwable first.
Once PHP 5.x support is no longer needed, the block catching Exception can be removed.

try
{
   // Code that may throw an Exception or Error.
}
catch (Throwable $t)
{
   // Executed only in PHP 7, will not match in PHP 5
}
catch (Exception $e)
{
   // Executed only in PHP 5, will not be reached in PHP 7
}
hungry dot rahly at gmail dot com 08-Jan-2016 12:26
You can catch both exceptions and errors by catching(Throwable)