我试图弄清楚在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异常手册:
当抛出异常时,语句后面的代码将不会被执行,PHP将尝试找到第一个匹配的catch块。如果未捕获异常,则会发出带有“Uncaught Exception…”消息的PHP致命错误,除非使用
set_exception_handler()
定义了处理程序。
throw
语句后的代码不会被执行。这和return
语句很相似。
catch
,停止其展开所述堆栈)... - user166390