Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

try-except inside a loop

Tags:

python

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
like image 573
akonsu Avatar asked Nov 09 '11 17:11

akonsu


People also ask

Can you put a try except in while loop?

Python while loop exception continue If a statement is systematically correct then it executes the programm. Exception means error detection during execution. In this example, we can easily use the try-except block to execute the code.

How do you use try and except in for loop in Python?

The try block lets you test a block of code for errors. The except block lets you handle the error. The else block lets you execute code when there is no error.

Can you use try catch in a loop Java?

If you have try catch within the loop it gets executed completely inspite of exceptions.


1 Answers

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.

like image 198
phihag Avatar answered Oct 23 '22 15:10

phihag