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

Spe*_*ark 18 php exception

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

Kai*_*aii 38

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

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

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;
Run Code Online (Sandbox Code Playgroud)

有关异常,请参阅PHP手册:

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


Mad*_*iha 6

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