It completely depends on the nature of the failure and what you intend to do in catch .
But I would generalize it like this:
- If you want the loop to exit Exception, wrap the whole loop
- If you want the cycle to continue, do not
EDIT
Exceptions detected inside the loop 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; }
exit:
1 2 Exception at 3 4 5 Exception at 6 7 8 Exception at 9
While those who fall 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
Peter Bailey
source share