PHP:try-catch-finally 在循环中,在 catch 中继续
Posted
技术标签:
【中文标题】PHP:try-catch-finally 在循环中,在 catch 中继续【英文标题】:PHP: try-catch-finally in loop with continue in catch 【发布时间】:2020-02-25 09:20:58 【问题描述】:好的,关于上面代码的技术问题:
foreach($x as $y) // or even a simple for()
try
a();
catch(\Exception $e)
// just skip current iteration
continue;
finally
c();
由于c()
在finally
块中,它应该总是被执行,但是continue
语句呢?
根据documentation,它似乎正在跳过finally
块。
那么,c()
是否会在a()
抛出异常的情况下执行?
【问题讨论】:
【参考方案1】:使用控制台很容易发现。类型
php -r 'foreach([1, 2] as $n)try echo "\n", $n, "\n"; throw new \Exception(); catch (\Exception $e) continue; finally echo "finally has been called";'
这是代码的单字符串表示
foreach ([1, 2] as $n)
try
echo "\n", $n, "\n";
throw new \Exception();
catch (\Exception $e)
continue;
finally
echo "finally has been called";
你会得到
1
finally has been called
2
finally has been called
【讨论】:
以上是关于PHP:try-catch-finally 在循环中,在 catch 中继续的主要内容,如果未能解决你的问题,请参考以下文章
Java中使用try-catch-finally处理IO流中的异常
try-catch-finally 中哪个部分可以省略?try-catch-finally 中,如果 catch 中 return 了,finally 还会执行吗?