Try, except...retry?

Alex Martelli aleax at aleax.it
Thu Nov 13 16:51:23 CET 2003


Isaac To wrote:
   ...
>     try:
>         x1 = could_raise_an_exception(1)
>         x2 = could_raise_an_exception(2)
>         x3 = could_raise_an_exception(3)
>         x4 = could_raise_an_exception(4)
>         process(x1)
>         process(x2)
>         process(x3)
>         process(x4)
>     except Exception, err:
>         deal_with_exception(err)
>     proceed_here()
> 
> to be a better alternative than the corresponding code when all the
> excepts are written out in else parts, just because it is easier to
> understand.

So is "a + b" easier to understand than math.hypot(a, b) -- but if
what you need to compute is the square root of a**2 plus b**2, the
"ease of understanding" a very different computation means nothing.

How do you KNOW that function 'process' cannot raise an exception
(e.g., that it has no bugs) or, if it does, deal_with_exception
will be able to uniformly handle any exception coming from EITHER
process (on ANY of the x's, too) OR any of the several calls to
could_raise_an_exception?

It is extremely unlikely (though not impossible) that this structure
is actually best for a given set of needs.  When it isn't, what
you're doing is setting up a trap for yourself here.

Let's assume, for example, that deal_with_exception IS able to 
uniformly handle ANY exception whatsoever raised by any call to
could_raise_an_exception, but NO exceptions are expected from any 
of the calls to process.

If this is the case, then, if you make it a habit to program like 
this, it WILL eventually cost you some unpredictable but likely 
large amount of debugging time.  A bug will be introduced during
a refactoring of function 'process', or an 'x' will be generated
that is inappropriate for the function, etc, etc.  The bug will
be swallowed and hidden by the too-wide "except" clause.  Unit
tests will fail mysteriously (assuming you have them: people who
botch up program structure this way are unfortunately likely to
think that unit tests are too much trouble, not "easy to understand"
enough, or the like... -- or else, worse!!!, wrong but semi-plausible
results will come out of your program...!).  The best wish I can
make is that the resulting utter waste of hours, days, whatever,
will fall on the head of whoever IS responsibile for promoting or
using this wrong structure, and not on some poor hapless maintainer
coming later onto the scene of the crime.


Alex





More information about the Python-list mailing list