gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 02:55:24 25 4
gpt4 key购买 nike

我对这些术语及其在 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com