Try, except...retry?

Peter Otten __peter__ at web.de
Thu Nov 13 08:05:12 EST 2003


Isaac To wrote:

> Hmmm...  I agree only with reservation.  The primary advantage of
> exceptions, rather than other error reporting mechanisms like a return
> value, is that you can group a lot of statements and have a single block
> of
> code handling all of those.  This way you can separate the error handling
> code and the normal code, to make the whole logic clearer.  So if the
> exception doesn't happen often enough to warrant the effort, I consider
> the one at the begining, i.e.,
> 
>     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.

I would prefer:

x1 = x2 = x3 = x4 = None
try:
    x1 = acquireRessource(1)
    x2 = acquireRessource(2)
    x3 = acquireRessource(3)
    x4 = acquireRessource(4)
    process(x1, x2, x3, x4)
finally:
    if x1: releaseRessource(x1)
    if x2: releaseRessource(x2)
    if x3: releaseRessource(x3)
    if x4: releaseRessource(x4)

where acquireRessource() should try hard to deal with potential exceptions
and only pass the fatal ones to the caller. Exceptions occuring when
processing the ressource should be dealt with in process() if possible. As
for process() working orthoganally on xi, that does not make any sense to
me. In such cases, be generous and provide a try ... finally and/or except
for every ressource.

Now back to else:

try:
    x = canRaise()
    cannotRaise(x)
except Exception, e:
    dealWithException(e)

You must be very confident in your code to assume that cannotRaise() will
never raise an exception that dealWithException() will then accidentally
handle. So after a short phase of accommodation,

try:
    x = canRaise()
except Exception, e:
    dealWithException(e)
else:
    cannotRaise(x) # may still be lying

is both more readable and better code (neglecting for the moment the
redundancy that many python coders will find in these attributes :-)


Peter





More information about the Python-list mailing list