PHP-try-catch inner loop

Is it really less efficient to put a try-catch block inside a loop rather than wrapping a loop with try-catch in php if the loop is supposed to end if an exception occurs? Or is there no difference?

EDIT:

i.e.,

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

against

 try { foreach (/*...*/) { //... } } 
+8
performance php try-catch
source share
4 answers

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 
+30
source share

Most likely, there is no difference. Optimization at this level usually makes no sense in an interpreted language such as PHP.

In most cases, your logic will require you to place the block inside the loop. Otherwise, the cycle will continue even if an error occurs.

+1
source share

Does it totally depend on how you use try-catch? Is it safe to continue looping through your object if an exception has been thrown?

+1
source share

Of course, there is a difference, in the most obvious way, in the first case you will only check for errors before entering the loop, if there are no exclusive throwers in the loop, leave it that way. On the other hand, you will check it at every iteration that you will need if you have suggestions or methods ... which may have exceptions.

I don’t know if I’ll explain myself well, let me know if you understand

0
source share

Source: https://habr.com/ru/post/650995/


All Articles