“throw new Exception”需要使用“exit()”吗?

19

我试图弄清楚在PHP中throw new Exception之后的代码是否仍然执行,我已经尝试过了,似乎没有输出任何内容,但是仍然想确定一下。


我想知道异常的意义是什么,如果它不会引起堆栈展开(直到适当的条件,例如 catch,停止其展开所述堆栈)... - user166390
8
当抛出异常时,该语句后面的代码将不会被执行,并且PHP将尝试寻找第一个匹配的catch块。如果没有捕获到异常,则会发出一个带有“未捕获异常…”消息的PHP致命错误,除非已使用set_exception_handler()定义了处理程序。 - Michael Berkowski
2个回答

40

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

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

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块。如果未捕获异常,则会发出带有“Uncaught Exception…”消息的PHP致命错误,除非使用set_exception_handler()定义了处理程序。


6
不,throw语句后的代码不会被执行。这和return语句很相似。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接