Skip to content Skip to sidebar Skip to footer

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 retr

Solution 1:

Use try .. except .. else:

for i inrange(3, 0, -1):
  try:
    f()
  except IOError:
    if i == 1:
      raiseprint('retry')
  else:
    break

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

Solution 2:

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()

Solution 3:

To avoid ZeroDivisionError, as (3 / 0) or (3 % 0) will give us an Error.

lst= [2,4,10,42,12,0,4,7,21,4,83,8,5,6,8,234,5,6,523,42,34,0,234,1,435,465,56,7,3,43,23]

    lst_three= []

    for num in lst:try:if3%num==0:lst_three.append(num)except ZeroDivisionError:pass

Solution 4:

some items in the list are a string type, and we can't add a string to a number.

nums = [5, 9, '4', 3, 2, 1, 6, 5, '7', 4, 3, 2, 6, 7, 8, '0', 3, 4, 0, 6, 5, '3', 5, 6, 7, 8, '3', '1', 5, 6, 7, 9, 3, 2, 5, 6, '9', 2, 3, 4, 5, 1]

plus_four = []
for num in nums:
    try:
        plus_four.append(num+4)
    except:
        plus_four.append("Error")

Post a Comment for "Try-except Inside A Loop"