
Gennadiy Rozental wrote:
This code causes an exception being thrown to stop iteration. I just wonder if there is means to avoid it.
Out of curiosity, what's the problem with code throwing an exception, as long as it is properly caught ?
In general? Setting aside potential performance consequences, exceptions have to be used only to report error conditions, not as end of loop indicator.
Beside the fact that I completely agree with you (but probably because I'm a C++ developer), you have to be aware that Python and C++ philosophies differ dramatically. On this precise point, while C++ developers are attached to a well-defined balance between return codes and exceptions, Python has pushed the use of exceptions to an extreme. This often leads to things that are considered as worst practices and/or beginner mistakes in other languages, like the fact of stopping an iteration by throwing. In Python, the assertion that "exceptions should only handle errors" is unfortunately false. Bruno