When to use exceptions (was Re: reducing if statements...)

Don Dwiggins dwig at advancedmp.net
Tue Aug 21 19:24:53 EDT 2001


Alex Martelli writes:
> E.g., up to Python 2.1, whenever you code:
>     for x in asequence:
>         print x
> there will ALWAYS be an exception raised -- that's how the
> for statement knows the sequence is finished, by getting
> an IndexError exception from asequence[i] for some i.  Far
> from being 'exceptional', this must ALWAYS happen in ANY
> for statement that's not interrupted by break, return, or
> some other raise.  See -- exceptions are NOT only for
> exceptional cases, *in Python*.

Right, that's why they call them "exceptions" -- ummm, errr...

Alex, thanks for pointing this out.  I've been programming in Python for a
few months now, and this point never registered with me; as you mentioned, I
was thinking in "Java style".  A quick look at the tutorial in the
distribution docs and the relevant chapter in "Dive into Python" doesn't
mention this either.

So, are there some good patterns, idioms, or whatever to provide guidance on
when to use exceptions vs. checking error codes, etc. (other than the
obvious general qualities: ease of use, readability, modifiability, ...)?

-- 
Don Dwiggins                    "Solvitur Ambulando"
Advanced MP Technology
dwig at advancedmp.net





More information about the Python-list mailing list