Search code examples
phptry-catchbreakcontinue

Continue with current iteration in a try-catch block | PHP


In my script there are sometimes server, connection, configuration or API problems, hence I implemented a try-catch block to properly catch Exceptions and skip them.

... but my problem isn't solved with this solution as the elements (which threw a problem) aren't the problem itself. So basically my question is whether there is any way to catch the error and continue where you left of: Not skipping the error and going to the next element, but to repeat the current iteration in the foreach loop.

Obviously, continue and break don't work!

foreach($xx as $x) {
    try {
        //main code
    } catch (Exception $e) {
        echo 'Caught exception: ', $e->getMessage(), "\n";
        sleep(10);
    }
}

... and when the catch part catches the error the code is supposed to repeat the try loop with the current $x (on which it originally caught the error / threw the error) and then continue with the list of elements.


Solution

  • Put the try block into its own while (true) loop, which you can break on success:

    while (true) {
        try {
            ...
            break;
        } catch (...) {
            ...
        }
    }
    

    This retries the same action until no exception is thrown. To avoid endless loops on actions which will simply never succeed, you can add a counter like:

    $tries = 0;
    while ($tries < 10) {
        $tries++;
        try { ... }
    }