Search code examples
loopstry-catchphp-7continuetry-catch-finally

PHP: try-catch-finally in loop with continue in catch


Ok, just a technical question about the code above:

foreach($x as $y){ // or even a simple for()
    try{
        a();
    } catch(\Exception $e){
        // just skip current iteration
        continue;
    } finally {
        c();
    }
}

Since c() is in the finally block it should be always executed, but what about the continue statement?
According to the documentation it appears to be making the finally block being skipped.

So, does c() be executed in case of a() throwing an exception?


Solution

  • It's simple to discover just using console. Type

    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";}}'
    

    which is single-string representation of the code

    foreach ([1, 2] as $n) {
        try {
            echo "\n", $n, "\n";
            throw new \Exception();
        } catch (\Exception $e) {
            continue;
        } finally {
            echo "finally has been called";
        }
    }
    

    you'll get

    1
    finally has been called
    2
    finally has been called