The rap against "while True:" loops
steve at REMOVE-THIS-cybersource.com.au
Sat Oct 17 09:55:27 CEST 2009
On Fri, 16 Oct 2009 18:30:50 +0100, Tim Rowe wrote:
>> Also, using exceptions this way is a structured form of GOTO -- it's
>> easy to abuse and turn it into spaghetti code. Actually, not that easy
>> to abuse, because you can't jump back into the try block. It's more
>> like a multi-level break outside of a loop than a general GOTO.
> I don't think it's *only* the performance thing, it's also clarity. The
> understood meaning of throwing an exception is to say "something
> happened that shouldn't have". If one uses it when something has
> happened that *should* have, because it happens to have the right
> behaviour (even if the overhead doesn't matter), then one is
> misrepresenting the program logic.
No, you have a fundamental misunderstanding. They're called exceptions,
not errors, because they represent exceptional cases. Often errors are
exceptional cases, but they're not the only sort of exceptional case.
Python uses exceptions for flow control: e.g. for-loops swallow
StopIteration or IndexError to indicate the end of the loop. In the
context of a for-loop, StopIteration or IndexError doesn't represent an
error. It doesn't represent an unexpected case. It represents an
expected, but exceptional (special) case: we expect that most sequences
are finite, and it is normal to eventually reach the end of the sequence,
after which the loop must change behaviour.
Similarly, it's hardly an *error* for [1, 2, 3].index(5) to fail -- who
is to say that the list is supposed to have 5 in it? ValueError (a
slightly misleading name in this situation) is used to indicate an
exceptional, but not unexpected, occurrence.
Likewise, KeyboardInterrupt is used to allow the user to halt processing;
SystemExit is used to shut down the Python virtual machine; and warnings
are implemented using exceptions. There may be others among the built-ins
and standard library, but even if there aren't, there is plenty of
precedence for us to do the same.
More information about the Python-list