简体   繁体   中英

try-except inside a loop

I need to invoke method f . If it raises an IOError , I need to invoke it again (retry), and do it at most three times. I need to log any other exceptions, and I need to log all retries.

the code below does this, but it looks ugly. please help me make it elegant and pythonic. I am using Python 2.7.

thanks!

count = 3
while count > 0:
    try:
        f()
    except IOError:
        count -= 1
        if count > 0:
            print 'retry'
        continue
    except Exception as x:
        print x
    break

Use try .. except .. else :

for i in range(3, 0, -1):
  try:
    f()
  except IOError:
    if i == 1:
      raise
    print('retry')
  else:
    break

You should not generically catch all errors. Just let them bubble up to the appropriate handler.

You can write a retry decorator:

import time

def retry(times=3, interval=3):
    def wrapper(func):
        def wrapper(*arg, **kwarg):
            for i in range(times):
                try:
                    return func(*arg, **kwarg)
                except:
                    time.sleep(interval)
                    continue
            raise
        return wrapper
    return wrapper


//usage
@retry()
def fun():
    import inspect; print inspect.stack()[0][3]
    return "result"

print fun()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM