php - 既然所有错误都是异常,PHP7 上的 set_error_handler() 会发生什么?

标签 php error-handling exception-handling php-7

在 PHP5 上,同时定义 set_exception_handler()set_error_handler() 非常有意义。

但是,在 PHP7 上,所有(大多数?)错误现在都是异常。那么,如果错误会由异常处理程序传递,那么定义这两个处理程序有什么意义呢?

我看到异常处理程序文档中有关于 PHP7 新 Error 类的注释,但没有提到不再有明显错误的事实,而是 Throwable,在错误处理函数中。

Since PHP 7, most errors are reported by throwing Error exceptions, which will be caught by the handler as well. Both Error and Exception implements the Throwable interface. [source]

最佳答案

Aaron Piotrowski(开发新错误异常系统的人)有一个 great blog on this .我认为你需要了解的关键点是这个

In PHP 7, an exception will be thrown when a fatal and recoverable error (E_ERROR and E_RECOVERABLE_ERROR) occurs, rather than halting script execution. Fatal errors still exist for certain conditions, such as running out of memory, and still behave as before by immediately halting script execution. An uncaught exception will also continue to be a fatal error in PHP 7. This means if an exception thrown from an error that was fatal in PHP 5.x goes uncaught, it will still be a fatal error in PHP 7.

Note that other types of errors such as warnings and notices remain unchanged in PHP 7. Only fatal and recoverable errors throw exceptions.

换句话说,考虑这个

  • set_exception_handler() - 默认处理 Exception 的函数(从 PHP 7.0 开始,它可以处理所有 Throwable,因此它可以捕获可恢复的错误)
  • set_error_handler() - 处理可恢复错误的函数

换句话说,它们的功能没有改变。任何在 PHP5 中触发它们的东西都会在 PHP7 中触发它们,只是现在,您可以在脚本级别使用 try-catch block 来处理特定错误。

关于php - 既然所有错误都是异常,PHP7 上的 set_error_handler() 会发生什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40361353/

相关文章:

php - 无法从php中删除mysql数据

php - 当 mysql 查询终止但查询在 dbms 中工作时如何修复我的代码?

PHP SimpleXML 不保留 XML 属性中的换行符

node.js - 表达:下一个(错误)堆栈跟踪

powershell - 抛出消息未显示

c++ - 崩溃处理程序打印回溯

javascript - `throw new Error`和 `throw someObject`有什么区别?

php - 从页面和发布永久链接中删除侧边栏

bash - 循环让 youtube-dl 下载其中一种格式(取决于错误)

python - 将重试封装到 `with` block 中