PHP:try-catch-finally循环执行,catch继续执行

问题描述 投票:0回答:1

好吧,只是有关上面代码的技术问题:

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()

loops try-catch php-7 continue try-catch-finally
1个回答
0
投票

仅使用控制台即可发现。类型

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
© www.soinside.com 2019 - 2024. All rights reserved.