Try, except...retry?

Isaac To kkto at csis.hku.hk
Wed Nov 12 22:39:57 EST 2003


>>>>> "Robert" == Robert Brewer <fumanchu at amor.org> writes:

    >> One sign that somebody has moved from "Python newbie" to "good Python
    >> programmer" is exactly the moment they realize why it's wrong to
    >> code:
    >> 
    >> try:
    >>     x = could_raise_an_exception(23)
    >>     process(x)
    >> except Exception, err:
    >>     deal_with_exception(err)
    >> proceed_here()
    >> 
    >> and why the one obvious way is, instead:
    >> 
    >> try:
    >>     x = could_raise_an_exception(23)
    >> except Exception, err:
    >>     deal_with_exception(err)
    >> else:
    >>     process(x)
    >> proceed_here()

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.

Regards,
Isaac.




More information about the Python-list mailing list