PHP:异常和可捕获的 fatal error 有什么区别?

标签 php exception exception-handling try-catch fatal-error

我对这些术语及其在 PHP 中的确切含义/处理感到有点困惑:

Exception 可以这样定义:

When an error occurs within a method, the method creates an object and hands it off to the runtime system. The object, called an exception object, contains information about the error, including its type and the state of the program when the error occurred. Creating an exception object and handing it to the runtime system is called throwing an exception.

可以捕获和处理异常。

fatal error 可以这样定义:

Fatal errors are critical errors - for example, instantiating an object of a non-existent class, or calling a non-existent function. These errors cause the immediate termination of the script, and PHP's default behavior is to display them to the user when they take place.

fatal error 不一定能被捕获(它们不会抛出通常的异常),否则就不会有更具体的Catchable Fatal Error

但是,Catchable Fatal Error 与普通的Exception 有何不同?它的处理方式一样吗?可捕获的 fatal error 是否是特定类型的异常?

最佳答案

Fatal errors can not necessarily be caught (they do not throw usual exceptions)

在版本 7 之前,情况就是这样。用于阻止脚本停止运行的 fatal error 。但是,从版本 7 开始,它们现在显示为可捕获的异常。这使您可以从非常重要的问题中优雅地恢复。

However how is a Catchable Fatal Error different from a normal Exception?

它们都实现了 Throwable,但具有不同的 anchor 类:

Throwable
    Error
        ParseError
        ...
    Exception
        RuntimeException
        ...

And is it handled the same?

是的,您可以捕获它们,就像异常一样。

Is a catchable fatal error a specific type of exception or not?

取决于你的语义。如果您明白我的意思,可捕获的 fatal error 是一个异常,但它不是 Exception。可以这样区分;

// "traditional" exceptions
try {
    throw new Foo();
} catch (Exception $e) {
}

// v7 catchable fatal errors
try {
    $not_an_object->not_a_method();
} catch (Error $e) {
}

// both
try { 
} catch (Throwable $e) {
}

关于PHP:异常和可捕获的 fatal error 有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49675406/

相关文章:

perl - perl eval "...propagated"记录在哪里

php - Laravel 5 - 我如何处理 MethodNotAllowedHttpException

php - 正则表达式匹配两个静态 url 组件之间的部分

javascript - Ajax/Jquery 问题将数据推送到后端

java - FileNotFoundException 未被 IOException 捕获

java - 将异常记录到文件

python - 如何返回值并引发异常

node.js - 如何在 node.js 中捕获 zlib 错误

php - 结合 PHP exec、form 和 linux

javascript - 尝试使用 PHP/Javascript 构建可点击的索引,显示每个点击项目的数据