Exceptions as a Control Structure

Olivier Parisy olivier.parisy at free.fr
Mon Aug 9 15:26:05 CEST 2004

Peter Hansen wrote:

> In Python, very little is frowned upon solely for efficiency
> reasons.  There are some examples, including using +=
> repeatedly to grow a string, and some fields where efficiency
> is of course critical, but in Python one almost always looks
> for the most pragmatic approach (which is often the most
> elegant, too, for some people's definition of elegant)
> rather than obsessing about speed.

I understand this. That's one of the reasons I am learning
Python (I am more interested in improving my development time
than my programs' execution time).

>> Are exceptions
>> considered as reasonable control structures, or is
>> StopIteration alone of its kind ?
> Catching an exception is considered a reasonable approach
> to flow control for various problems.  One, for example,
> is in deeply nested loops, where rather than going out of
> one's way to avoid exceptions in favour of a flag and lots
> of awkward testing, one just raises a custom exception
> (or perhaps a standard one) and catches it outside the
> loops.

OK. Definitely not something I'd do in C++.

> Exceptions are also used by some as a mechanism for
> returning information from subroutines, though it's
> very likely the information will still be considered
> "exceptional" in some way (think of it as an out-of-band
> mechanism for returning special info).

Do you have some example of this in the standard library ?

> While some people object on stylistic grounds (or even
> performance ones, in some cases) to such things, you
> will likely find that exceptions are thrown around
> by Python programmers more readily than you are used to.

That's what I wanted to know. OK.

> Note also that in many cases other than algorithmic
> complexity, what you have learned about efficiency in
> C++ should be considered suspect info when it comes
> to Python.  Function calls, for example, are much more
> expensive in Python than in C++ because of the time
> required to set up the call frame.  Exceptions, on the
> other hand, are as I recall much more efficient.

So I suppose I just won't concern myself with efficiency
questions and concentrate on prope style, then.

> Some Google Group searches in c.l.p would probably
> lead to many past discussions of these things.

I must admit I probably didn't do my homework...
BTW, thanks for your reactivity !


More information about the Python-list mailing list