Why does Throwable catch ignore 'continue' but it does work with 'return'?

132 Views Asked by At

I have the following code:

foreach ($inDomainLinks as $href) {
    try {
        $page->goto($href, ['waitUntil' => 'networkidle2']);
    } catch (\Throwable $exception) {
        continue;
    }
}

I would like that if the code inside Try fails, we continue to the next value in the loop.

However, the code above throws the error anyway and the execution ends.

If I try to do this for instance:

foreach ($inDomainLinks as $href) {
    try {
        $page->goto($href, ['waitUntil' => 'networkidle2']);
    } catch (\Throwable $exception) {
        return $href.' fails';
    }
}

It actually returns that value, so I'm actually reaching the catch, but I just don't know why the first code doesn't execute as intended (by me).

Any ideas?

So far my workaround is creating a private function that wraps the try catch:

foreach ($inDomainLinks as $href) 
    $this->analyzePage($page,$href);

private function analyzePage($page,$href){
    try {
        $page->goto($href, ['waitUntil' => 'networkidle2']);
        return true;
    } catch (\Throwable $exception) {
        return false;
    }
}
1

There are 1 best solutions below

6
g9m29 On

If it throws the error then you are not catching the correct error. The continue will work there, and to be honest it is redundant since the code will go anyway.