[Tutor] functions: use return or exceptions?

Steven D'Aprano steve at pearwood.info
Fri Sep 24 03:06:09 CEST 2010


On Fri, 24 Sep 2010 05:47:21 am Wayne Werner wrote:

> OTOH, a lot of people feel that using exceptions as control flow is
> bad practice - they're exceptional so they should only arise in
> exceptional case.

That's not the Python philosophy. Python uses exceptions for flow 
control: iteration catching StopIteration is just the most common 
example. There's nothing wrong with using exceptions in your own code 
for the same purpose.

Note carefully that exceptions *cannot* be used to implement 
unstructured GOTOs, since you can't jump into the middle of a function, 
or backwards.

Speaking of GOTO, and it's even more evil cousin COME FROM, see this 
wonderful April 1st joke:

http://mail.python.org/pipermail/python-announce-list/2004-April/002982.html


> There may be performance issues, though I'm not familiar enough with
> that yet.

Setting up a try...except block is fast, about as fast as the "pass" 
statement. "Do nothing" is about as fast as you can get in Python, so 
you need not fear wrapping things in a try block.

But catching an exception is about 100 times more expensive. If you're 
using *lots* of exceptions for flow control, then your code will 
probably be slow. A single exception to end the flow, like 
StopIteration, doesn't matter.



-- 
Steven D'Aprano


More information about the Tutor mailing list