exceptions == errors?

Erik Max Francis max at alcyone.com
Mon Apr 7 20:10:00 EDT 2003


Mark Harrison wrote:

> Are exceptions always considered errors, or there the same feeling
> as in C++ that exceptions can be used for non-error situations?

Even moreso than in C++; in Python, exceptions are often used internally
for flow control.  By default an iteration protocol will iterate over an
object with the subscription operator, using successively high indices,
until it hits an IndexError, at which point it stops:

>>> class C:
...  def __getitem__(self, index):
...   if index < 10:
...    return index**2
...   else:
...    raise IndexError
... 
>>> [x for x in C()]
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

> Therefore, I'm thinking of structuring the code like this:
> 
>         while 1:
>                 try:
>                         read request
>                         process request
>                 catch MyException,e:
>                         send response contained in e
>                 catch Exception,e:
>                         send "internal error" response
> 
> Am I setting myself up for trouble if I follow this route?
> All advice gratefully received.

The only potential flaw that I see here is one with a standard "catch
all" phrase.  In C++ this generally isn't a problem, since you have a
compile phase and so syntax errors and typos will get caught before the
program runs, but in a dynamic language like Python you can find
yourself in headaches where something's failing and you have no idea
why, until you finally track it down and realize you spelled a variable
wrong, which was generating a NameError, but was being caught by your
catch Exception: ... clause.

Once you're cognizant of the problem, it's not as much of an issue, but
it might bite you the first time (or few times) before you get used to
it.

-- 
 Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/
 __ San Jose, CA, USA / 37 20 N 121 53 W / &tSftDotIotE
/  \ Blood is the god of war's rich livery.
\__/ Christopher Marlowe
    Computer science / http://www.alcyone.com/max/reference/compsci/
 A computer science reference.




More information about the Python-list mailing list