coding style - try, except

Scott David Daniels Scott.Daniels at Acm.Org
Wed Feb 25 13:22:46 EST 2009


RGK 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....
>   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?
What's wrong with:
     try:
         do something 1
         do something 2
     except (AttributeError, ValueError), why: # Don't use bare except
         print "Oops something didn't work: %s" % why
     else:
         do something 3
         do something 4
         ...
         do something 25
--Scott David Daniels
Scott.Daniels at Acm.Org



More information about the Python-list mailing list