PHP: try-catch-finally 在循环中,在 catch 中继续
PHP: try-catch-finally in loop with continue in catch
好的,只是关于上面代码的技术问题:
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()
抛出异常的情况下执行?
使用控制台很容易发现。输入
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
好的,只是关于上面代码的技术问题:
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()
抛出异常的情况下执行?
使用控制台很容易发现。输入
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