gpt4 book ai didi

php - 'throw new Exception' 是否需要 exit()?

转载 作者:IT王子 更新时间:2023-10-29 00:06:15 34 4
gpt4 key购买 nike

我正在尝试确定位于 PHP 中 throw new Exception 之后的代码是否仍在执行 - 我已经尝试过了,它似乎没有输出任何内容,但我想知道肯定的。

最佳答案

不,抛出异常后的代码不执行。

在这个代码示例中,我用数字标记了将要执行的行(代码流):

try {
throw new Exception("caught for demonstration"); // 1
// code below an exception inside a try block is never executed
echo "you won't read this." . PHP_EOL;
} catch (Exception $e) {
// you may want to react on the Exception here
echo "exception caught: " . $e->getMessage() . PHP_EOL; // 2
}
// execution flow continues here, because Exception above has been caught
echo "yay, lets continue!" . PHP_EOL; // 3
throw new Exception("uncaught for demonstration"); // 4, end

// execution flow never reaches this point because of the Exception thrown above
// results in "Fatal Error: uncaught Exception ..."
echo "you won't see me, too" . PHP_EOL;

参见 PHP manual on exceptions :

When an exception is thrown, code following the statement will not be executed, and PHP will attempt to find the first matching catch block. If an exception is not caught, a PHP Fatal Error will be issued with an "Uncaught Exception ..." message, unless a handler has been defined with set_exception_handler().

关于php - 'throw new Exception' 是否需要 exit()?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11214895/

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