coding style - try, except

Chris Rebert clp2 at rebertia.com
Wed Feb 25 19:08:55 CET 2009


On Wed, Feb 25, 2009 at 9:36 AM, RGK <blank at empty.blank> wrote:
>
> I'm still learning, so eager to see if there is some community wisdom about
> use of the try/except structures in this situation.
>
> I find myself with some potentially risky stuff and wrap it in a try/except
> structure with good functional results, though my code leaves me a bit
> uneasy. Maybe it's just esoteric, but your input is appreciated.
>
> Consider
>
>  try:
>    do something 1
>    do something 2
>    do something 3
>    do something 4
>    ...
>    do something 25
>
>  except:
>    print "Oops something didn't work"
>
>
> The risky things are just 1 & 2, and the others are not of concern, but are
> dependent on 1 & 2.  The alternative is to do:
>
>  wentOkay = True
>  try:
>    do something 1
>    do something 2
>
>  except:
>    print "Oops something didn't work"
>    wentOkay = False
>
>  if wentOkay:
>    do something 3
>    do something 4
>     ...
>    do something 25
>
>
> Which seems a bit verbose, but likely the better approach.  Is there some
> other option I should be considering?

Yes. try-except-*else*.

try:
    do_something_1()
    do_something_2()
except:
    print "Houston, we have a problem"
else: #runs only if no exception was thrown
    do_something_3()
    do_something_4()
    et_cetera()

Cheers,
Chris

-- 
Follow the path of the Iguana...
http://rebertia.com



More information about the Python-list mailing list