gpt4 book ai didi

PHP 尝试,捕获优先级和继承

转载 作者:行者123 更新时间:2023-12-03 22:56:28 28 4
gpt4 key购买 nike

我想知道一些关于 PHP 的 try , catch声明。

让我们考虑以下示例。

abstract class ExceptionA extends Exception
{}

class ExceptionB extends ExceptionA
{}

class ExceptionTest
{
public function example()
{
try {
throw new ExceptionB();
} catch ( ExceptionB $e ) {
echo 'ExceptionB was caught';
} catch ( ExceptionA $e ) {
echo 'ExceptionA was caught';
} catch ( Exception $e ) {
echo 'Exception was caught';
}
}
}

全部 catch语句匹配异常。其中第一个 ( ExceptionB ) 是最接近的匹配项。

请问 catch的顺序哪些言论会受到影响呢?

最佳答案

the manual :

When an exception is thrown, code following the statement will not be executed, and PHP will attempt to find the first matching catch block.



您可以轻松确认:

捕捉 ExceptionB第一的:
class ExceptionTest
{
public function example()
{
try {
throw new ExceptionB();
} catch (ExceptionB $e) {
echo 'ExceptionB was caught';
} catch (ExceptionA $e) {
echo 'ExceptionA was caught';
} catch (Exception $e) {
echo 'Exception was caught';
}
}
}

(new ExceptionTest())->example(); // Exception B was caught

演示:https://3v4l.org/htgEg

捕捉 ExceptionA首先和 ExceptionB后:
class ExceptionTest
{
public function example()
{
try {
throw new ExceptionB();
} catch (ExceptionA $e) {
echo 'ExceptionA was caught';
} catch (ExceptionB $e) {
echo 'ExceptionB was caught';
} catch (Exception $e) {
echo 'Exception was caught';
}
}
}

(new ExceptionTest())->example(); // Exception A was caught

演示:https://3v4l.org/J7Xul

关于PHP 尝试,捕获优先级和继承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59686240/

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