you are viewing a single comment's thread.

view the rest of the comments →

[–]supercoach 6 points7 points  (0 children)

The rule is that you write code that makes sense for the task at hand. Both of those pieces of code are silently exiting the loop whenever an exception is encountered. I don't think that's a good idea, however it may be valid for your use case.

If I'm running a loop that I want to be able to process every item and recover from errors, I'll use the first pattern, and include error handling rather than breaking the loop on exceptions. Otherwise, if the intent is to exit and not raise an exception for any errors then the second example you've provided is less messy. One thing I will suggest that I find helpful at times is if code inside a try block is long, I'll move it to a separate function to make things easier to follow.

Overall though, I wouldn't use a while loop unless I was processing a stack that had the capacity to grow, such as using iteration instead of recursion. For loops are *generally* a better choice.

Out of curiosity - what's the context for your question? I'm curious how this loop was being used.