“抛出新的异常”是否需要 exit()?

2022-08-30 20:47:24

我试图弄清楚PHP之后的代码是否仍在执行 - 我已经尝试过了,它似乎没有输出任何东西,但想知道确定。throw new Exception


答案 1

否,不会执行引发异常后的代码。

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

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 手册中的例外情况

当抛出异常时,语句后面的代码将不会执行,PHP 将尝试查找第一个匹配的 catch 块。如果未捕获异常,则会发出 PHP 致命错误,并显示“未捕获异常...”消息,除非已使用 定义处理程序。set_exception_handler()


答案 2

否,语句后面的代码不执行。很像.throwreturn


推荐