The rap against "while True:" loops
steve at REMOVE-THIS-cybersource.com.au
Thu Oct 15 01:11:04 CEST 2009
On Wed, 14 Oct 2009 20:17:40 +0000, Jorgen Grahn wrote:
>> But we have exceptions. And I know somebody, in other languages, thinks
>> it's a Best Practice to avoid using exceptions for flow control.
> A lot of C++ programmers think so, and Stroustrup himself says
> "exceptions are for exceptional things" or something to that effect. Is
> that what you're thinking of?
> Thankfully, Stroustrup doesn't use the dreaded phrase "Best Practice",
> which as far as I can tell is designed to shut down rational thought in
> the audience.
>> Thankfully, python programmers are less dogmatic, and use whatever
>> makes sense to use. I hope.
> Calling it "dogmatic" is unfair. C++ is very different from Python, and
> has a different implementation of exceptions. You also tend to use the
> language to solve a different set of problems.
> That said, I still don't fully understand the rationale behind that
> advice or rule ... so I'm willing to break it, and sometimes I do.
Setting up a try...except block is cheap in Python. According to my
tests, the overhead is little more than that of a single pass statement.
But actually raising and catching the exception is not cheap. If you use
a lot of exceptions for flow control, performance will probably suffer.
In C++, exceptions are expensive, whether you catch one or not.
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.
More information about the Python-list