Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP try-catch block inside loop [duplicate]

Is it less efficient to put a try-catch block inside of a loop as opposed to wrapping the loop with a try-catch in php if it is intended that the loop will end if an exception occurs? Or is there essentially no difference?

EDIT:

i.e.,

foreach (/*...*/) {
    //...
    try {
        //...
    } catch (/*...*/) {
        break;
    }
    //...
}

versus:

try {
    foreach (/*...*/) {
        //...
    }
}
like image 755
Uyghur Lives Matter Avatar asked Jan 12 '11 20:01

Uyghur Lives Matter


2 Answers

That entirely depends on the nature of the failure, and what you intend to do in the catch.

But I'd generalize it like so

  • If you want the loop to exit on Exception, wrap the whole loop
  • If you want the loop to continue, don't

EDIT

Exceptions caught inside a loop don't implicitly break the loop

for ($i = 1; $i < 10; $i++) {
    try {
        if ($i % 3 == 0) {
            throw new Exception('BOOM');
        }
        echo $i;
    } catch (Exception $e) {
        echo "Exception at $i";
    }
    echo PHP_EOL;
}

output:

1
2
Exception at 3
4
5
Exception at 6
7
8
Exception at 9

Whereas those caught outside the loop do

try {
    for ($i = 1; $i < 10; $i++) {
        if ($i % 3 == 0) {
            throw new Exception('BOOM');
        }
        echo $i, PHP_EOL;
    }
} catch ( Exception $e ) {
    echo "Exception at $i";
}

output:

1
2
Exception at 3
like image 83
Peter Bailey Avatar answered Oct 04 '22 05:10

Peter Bailey


That depends entirely on how you are using the try-catch? Is it safe to continue looping through your subject if an exception was thrown?

like image 36
Craige Avatar answered Oct 04 '22 04:10

Craige