PHP 异常会停止执行吗?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2302153/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Does a PHP exception stop execution?
提问by Not Joe Bloggs
<?php
function some_function($arg) {
if($filter->check_for_safe_input($arg)) {
throw new Exception("Hacking Attempt");
}
do_some_database_stuff($arg);
}
?>
In the above code example, does do_some_database_stuffever get called if check_for_safe_inputfails, or does the exception stop the function running? It's something I've never quite been sure of, and usually I just stick functions like do_some_database_stuffin an else statement to be sure, but this tends to lead to hugely nested functions.
在上面的代码示例中,do_some_database_stuff如果check_for_safe_input失败,是否会被调用,或者异常是否会停止函数运行?这是我从未完全确定的事情,通常我只是像do_some_database_stuff在 else 语句中那样坚持使用函数来确定,但这往往会导致大量嵌套的函数。
回答by Darin Dimitrov
Yes, uncaught exceptions result in fatal errors that stop the execution of the script. So the do_some_database_stufffunction will not be called if an exception is thrown. You can read more about exceptions in this article.
是的,未捕获的异常会导致停止执行脚本的致命错误。因此,do_some_database_stuff如果抛出异常,则不会调用该函数。您可以在本文中阅读有关异常的更多信息。
回答by svens
Have a look at the PHP manual on exceptions.
查看有关异常的 PHP 手册。
When an exception is thrown, code following the statement will not be executed, and PHP will attempt to find the first matching catch block. If an exception is not caught, a PHP Fatal Error will be issued with an "Uncaught Exception ..." message, unless a handler has been defined with set_exception_handler().
当抛出异常时,语句后面的代码不会被执行,PHP 会尝试找到第一个匹配的 catch 块。如果未捕获异常,将发出 PHP 致命错误并带有“未捕获的异常...”消息,除非已使用 set_exception_handler() 定义了处理程序。
So yes, the rest of the function is not being executed, a fata error occurs instead.
If you catch the exception, execution of the script continues in the corresponding catch block, everything "between" the function which throws an exception and the catch block is not executed.
所以是的,函数的其余部分没有被执行,而是发生了fata错误。
如果捕获异常,脚本的执行将在相应的 catch 块中继续执行,“介于”抛出异常的函数和 catch 块之间的所有内容都不会执行。
回答by Gordon
An exception, if not catched, will end script execution.
异常,如果没有被捕获,将结束脚本执行。
See the PHP manual chapter on Exceptions

