18

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

4

2 回答 2

39

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

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

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().

于 2012-06-26T19:51:50.313 回答
5

不,throw语句后面的代码不会被执行。很像return

于 2012-06-26T19:51:37.520 回答