avoiding nested try/excepts

Steven Bethard steven.bethard at gmail.com
Thu Nov 18 21:27:17 CET 2004


So I have code that looks something like this:

def f(xs):
     for x in xs:
         y = g(x) # can raise exception AnException
         for z in h(y):
             k(z) # can raise a variety of exceptions

Now, if g(x) raises AnException, I want to log something and skip the 
inner loop (but continue with the outer loop).  If k(z) raises an 
exception, I want to log something and then re-raise the exception to 
exit all the way out of f.  Currently I do something like:

def f(xs):
     for x in xs:
         try:
             y = g(x)
             for z in h(y):
                 k(z)
         except AnException, e:
             log(x, e)
         except:
             log(x)
             raise

I've heard before that it's generally a good idea to try to localize 
your try-except blocks as much as possible.  This would lead me to do 
something like:

def f(xs):
     for x in xs:
         try:
             y = g(x)
         except AnException, e:
             log(x, e)
         else:
             for z in h(y):
                 try:
                     k(z)
                 except:
                     log(x)
                     raise

but now I have another level of nesting and things get kinda hard for me 
to read.  So I have two questions:

(1) Should I really worry about localizing try-except blocks? and, if so
(2) Is there a cleaner way to do this kind of thing?

Note that I can't edit the g or k functions, so I can't move the 
try-except blocks inside.

Thanks,

Steve



More information about the Python-list mailing list