我正在试图弄清楚PHP中throw new Exception
之后的代码是否仍然执行 - 我已经尝试过了,它似乎没有输出任何东西,但想肯定地知道。
答案 0 :(得分:35)
不,抛出异常后的代码不会被执行。
在这个代码示例中,我用数字标记了要执行的行(代码流):
try {
throw new Exception("caught for demonstration"); // 1
// code below inside the 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!" . 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将尝试查找第一个匹配的catch块。如果未捕获到异常,将发出一个PHP致命错误,其中包含"未捕获的异常..."消息,除非已使用
set_exception_handler()
定义了处理程序。
答案 1 :(得分:4)
不,throw
语句后的代码未执行。很像return
。