The rap against "while True:" loops

Tim Rowe digitig at gmail.com
Sat Oct 17 08:12:52 EDT 2009


2009/10/17 Steven D'Aprano <steve at remove-this-cybersource.com.au>:

> 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.

The whole reason for the mechanism, across all languages that have it,
is to deal with situations that you don't know how to deal with
locally. That's why they have the overhead that they do.

> Python uses exceptions for flow control:

Yes, and in some cases I think that's a serious language wart. Not
enough to put me off the language, but a serious wart nevertheless.

> 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.

That one is, I think, a legitimate use of an exception. The result
returned by index is defined if the index is in bounds. If not, index
doesn't know whether it was supposed to be in bounds or not, and so
can't handle the case locally. It could suggest an error or merely
(IMHO) poor programming. Because index cannot know what the proper
action is, an exception is the appropriate response.

> 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.

Again, I think it's fair to treat a program being killed from outside
as an exception as far as the program is concerned. They're not things
the program has brought about, and the original handling code has no
way of knowinng what response is appropriate. Same with warnings; they
*probably* shouldn't happen but only the application programmer can
know whether they should or not.

The point is that an exception causes a change in program flow, so of
course they're used for flow control. It's what they do. The question
is in what cases it's appropriate to use them.

-- 
Tim Rowe



More information about the Python-list mailing list