Python continue on error

Python 'continue' is a loop statement. It stops the current iteration of a loop and starts the next iteration. It does not stop the loop.

Python continue statement is one of the loop statements that control the flow of the loop. More specifically, the continue statement skips the “rest of the loop” and jumps into the beginning of the next iteration.

Unlike the break statement, the continue does not exit the loop.

For example, to print the odd numbers, use continue to skip printing the even numbers:

n = 0
while n < 10:
    n += 1
    if n % 2 == 0:
        continue
    print(n)

This loop skips the print function when it encounters an even number (a number divisible by 2):

1
3
5
7
9

Here is an illustration of how the above code works when n is even:

Python continue statement

Continue Statement in More Detail

In Python, the continue statement jumps out of the current iteration of a loop to start the next iteration.

A typical use case for a continue statement is to check if a condition is met, and skip the rest of the loop based on that.

Using the continue statement may sometimes be a key part to make an algorithm work. Sometimes it just saves resources because it prevents running excess code.

In Python, the continue statement can be used with both for and while loops.

while condition:
    if other_condition:
        continue

for elem in iterable:
    if condition:
        continue

For instance, you can use the continue statement to skip printing even numbers:

n = 0
while n < 10:
    n += 1
    if n % 2 == 0:
        continue
    print(n)

Output:

1
3
5
7
9

Continue vs If-Else in Python

The continue statement behaves in the same way as an if-else statement. Using the continue statement is essentially the same as putting the code into an if-else block.

In simple cases, it’s usually a better idea to use an if-else statement, instead of the continue!

For instance, let’s loop through numbers from 1 to 10, and print the type oddity of the numbers:

Here is the continue approach:

for num in range(1, 10):
    if num % 2 == 0:
        print("Even number: ", num)
        continue
    print("Odd number: ", num)

Output:

Odd number:  1
Even number:  2
Odd number:  3
Even number:  4
Odd number:  5
Even number:  6
Odd number:  7
Even number:  8
Odd number:  9

Then, let’s convert this approach to an if-else statement:

for num in range(1, 10):
    if num % 2 == 0:
        print("Even number: ", num)
    else:
        print("Odd number: ", num)

Output:

Odd number:  1
Even number:  2
Odd number:  3
Even number:  4
Odd number:  5
Even number:  6
Odd number:  7
Even number:  8
Odd number:  9

As you can see, the latter approach provides a cleaner way to express your intention. By looking at this piece of code it is instantly clear what it does. However, if you look at the former approach with the continue statements, you need to scratch your head a bit before you see what is going on.

This is a great example of when you can use an if-else statement instead of using the continue statement.

Also, if you take a look at the earlier example of printing the odd numbers from a range:

n = 0
while n < 10:
    n += 1
    if n % 2 == 0:
        continue
    print(n)

You see it is cleaner to use an if-check here as well, rather than mixing it up with the continue statement:

n = 0
while n < 10:
    n += 1
    if n % 2 != 0:
        print(n)

But now you may wonder why should you use continue if it only makes code more unreadable. Let’s see some good use cases for the continue statement.

When Use Continue Python

As stated earlier, you can replace the continue statement with if-else statements.

For example, this piece of code:

if condition:
    action()
    continue
do_something()

Does the same as this one:

if not condition:
    action()
else:
    do_something()

In simple cases, using if-else over a continue is a good idea. But there are definitely some use cases for the continue statement too.

For example:

  1. You can avoid nested if-else statements using continue.
  2. Continue can help you with exception handling in a for loop.

Let’s see examples of both of these.

1. Avoid Nested If-Else Statements in a Loop with Continue in Python

Imagine you have multiple conditions where you want to skip looping. If you solely rely on if-else statements, your code becomes pyramid-shaped chaos:

for entry in data:
    if not condition1:
        action1()
        if not condition2:
            action2()
            if not condition3:
                action3()
            else:
                statements3()
        else:
            statements2()
    else:
        statements1()

This is every developer’s nightmare. A nested if-else mess is infeasible to manage.

However, you can make the above code cleaner and flatter using the continue statement:

for entry in data:
    if condition1:
        statements1()
        continue
    action1()
    
    if condition2:
        statements2()
        continue
    action2()
    
    if condition3:
        statements3()
        continue
    action3()

Now, instead of having a nested structure of if-else statements, you have a flat structure of if statements only. This means the code is way more understandable and easier to maintain—thanks to the continue statement.

2. Continue in Error Handling—Try, Except, Continue

If you need to handle exceptions in a loop, use the continue statement to skip the “rest of the loop”.

For example, take a look at this piece of code that handles errors in a loop:

for number in [1, 2, 3]:
  try:
    print(x)
  except:
    print("Exception was thrown...")
  print("... But I don't care!")

Now the loop executes the last print function regardless of whether an exception is thrown or not:

Exception was thrown...
... But I don't care!
Exception was thrown...
... But I don't care!
Exception was thrown...
... But I don't care!

To avoid this, use the continue statement in the except block. This skips the rest of the loop when an exception occurs.

for number in [1,2,3]:
  try:
    print(x)
  except:
    print("Exception was thrown...")
    continue
  print("... But I don't care!")

Now the loop skips the last print function:

Exception was thrown...
Exception was thrown...
Exception was thrown...

This is useful if the last print function was something you should not accidentally run when an error occurs.

Conclusion

Today you learned how to use the continue statement in Python.

To recap, the continue statement in Python skips “the rest of the loop” and starts an iteration. This is useful if the rest of the loop consists of unnecessary code.

For example, you can skip printing even numbers and only print the odd numbers by:

n = 0
while n < 10:
    n += 1
    if n % 2 == 0:
        continue
    print(n)

Here the loop skips the last print function if it encounters an even number.

However, an if-else statement is usually better than using an if statement with a continue statement. However, with multiple conditions, the continue statement prevents nested if-else blocks that are infeasible to manage.

Thanks for reading. I hope you enjoy it.

Happy coding!

Further Reading

50 Python Interview Questions with Answers

50+ Buzzwords of Web Development

About the Author

I’m an entrepreneur and a blogger from Finland. My goal is to make coding and tech easier for you with comprehensive guides and reviews.

Recent Posts

In this Python tutorial, we will discuss the Python While loop continue. Here we will also cover the below examples:

  • Python while loop continue break
  • Python while loop exception continue
  • Python nested while loop continue
  • Python while true loop continue
  • While loop continue python example
  • Python continue while loop after exception
  • Python try except continue while loop
  • Python while loop break and continue
  • Let us see how to use the continue statement in the While loop in Python.
  • Continue is used to skip the part of the loop. This statement executes the loop to continue the next iteration.
  • In python, the continue statement always returns and moves the control back to the top of the while loop.

Example:

Let’s take an example and check how to use the continue statement in the while loop

new_var = 8
while new_var >0:
    new_var=new_var-1
    if new_var==2:
        continue
    print(new_var)
print("loop end")

In the above code, we will first initialize a variable with 8 and check whether 8 is greater than 0. Here you can see it is true so I will go for a decrement statement that 8-1 and it will display the variable value as 7. it will check whether a variable is equal to 2. In the above code, you will check that it is not equal to the variable and it will print the value 7.

Here is the output of the following above code

Python while loop continue
Python while loop continue

Another example is to check how to use the continue statement in the while loop in Python.

Example:

z = 8
while z > 1:
    z -= 2
    if z == 3:
        continue
    print(z)
print('Loop terminate:')

Here is the screenshot of the following given code

Python while loop continue
Python while loop continue

Read: Python For Loop

Python while loop continue break

  • In python, the break and continue statements are jump statements. The break statement is used to terminate the loop while in the case of the continue statement it is used to continue the next iterative in the loop.
  • In the break statement, the control is transfer outside the loop while in the case of continue statement the control remains in the same loop.

Example:

while True:
    result = input('enter a for the loop: ')
    if result == 'a':
        break
print('exit loop')

a = 0
while a <= 8 :
    a += 1
    if a % 4 == 1 :
        continue
    print(a)

In the above code, we will create a while loop and print the result 2 to 8, But when we get an odd number in the while loop, we will continue the next loop. While in the case of the break statement example we will give the condition that if the user takes the input as ‘a’ it will exit the loop.

Output

Python while loop continue break
Python while loop continue break

Read: Python While Loop

Python while loop exception continue

  • Let us see how to use the exception method in the while loop continue statement in Python.
  • An exception is an event that occurs normally during the execution of a programm.
  • 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. Try is basically the keyword that is used to keep the code segments While in the case of except it is the segment that is actually used to handle the exception.

Example:

while True:
    try:
        b = int(input("enter a value: "))
        break
    except  ValueError:
        print("Value is not valid")

Screenshot of the given code

Python while loop exception continue
Python while loop exception continue

Read: Python While loop condition

Python nested while loop continue

  • Let us see how to use nested while loop in Python.
  • In this example, we will use the continue statement in the structure of the within while loop based on some important conditions.

Example:

Let’s take an example and check how to use nested while loop in Python

c = 2
while c < 4 :
    d = 1
    while d < 10 :
        if d % 2 == 1 :
            d += 1
            continue
        print(c*d, end=" ")
        d += 1
    print()
    c += 1

Here is the execution of the following given code

Python nested while loop continue
Python nested while loop continue

This is how to use nested while loop in python.

Python while true loop continue

In Python, the while loop starts if the given condition evaluates to true. If the break keyword is found in any missing syntax during the execution of the loop, the loop ends immediately.

Example:

while True:
    output = int(input("Enter the value: "))
    if output % 2 != 0:
        print("Number is odd")
        break
    
    print("Number is even")

In the above code, we will create a while loop and print the result whether it is an even number or not, when we get an odd number in the while loop, we will continue the next loop. In this example we take a user input when the user enters the value it will check the condition if it is divide by 2 then the number is even otherwise odd.

Here is the implementation of the following given code

Python while true loop continue
Python while true loop continue

Read: Python while loop multiple conditions

While loop continue Python example

  • Here we can see how to use the continue statement while loop.
  • In this example first, we will take a variable and assign them a value. Now when n is 4 the continue statement will execute that iteration. Thus the 4 value is not printed and execution returns to the beginning of the loop.

Example:

Let’s take an example and check how to use the continue statement in the while loop

l = 6
while l > 0:
    l -= 1
    if l == 4:
        continue
    print(l)
print('Loop terminate')

Output

while loop continue python example
while loop continue python example

Another example to check how to apply the continue statement in the while loop

Example:

t = 8                  
while 8 > 0:              
   print ('New value :', t)
   t = t-1
   if t == 4:
      break

print ("Loop end")

Here is the output of the program

While loop continue Python example
While loop continue Python example

Read: Python dictionary length

Python try except continue while loop

  • Here we can check how to apply the try-except method in the continue while loop.
  • In this example, I want to convert the input value inside a while loop to an int. In this case, if the value is not an integer it will display an error and continue with the loop.

Example:

m=0
new_var=0
l = input("Enter the value.")
while l!=str("done"):
     try:
          l=float(l)
     except:
          print ("Not a valid number")
          continue
     m=m+1
     new_var = l + new_var      
     l= input("Enter the value.")
new_avg=new_var/m
print (new_var, "g", m, "g", new_avg)

Here is the implementation of the following given code

Python try except continue while loop
Python try-except continue while loop

Python while loop break and continue

  • In Python, there are two statements that can easily handle the situation and control the flow of a loop.
  • The break statement executes the current loop. This statement will execute the innermost loop and can be used in both cases while and for loop.
  • The continue statement always returns the control to the top of the while loop. This statement does not execute but continues on the next iteration item.

Example:

Let’s take an example and check how to use the break and continue statement in while loop

k = 8                    
while k > 0:              
   print ('New value :', k)
   k = k -1
   if k == 4:
      break

print ("loop terminate")

b = 0
while b <= 8 :
    b += 1
    if b % 4 == 1 :
        continue
    print(b)
  

Output:

Python while loop break and continue
Python while loop break and continue

This is how to use the break and continue statement in while loop

You may also like reading the following articles.

  • Registration form in Python using Tkinter
  • Extract text from PDF Python
  • Python loop through a list
  • For loop vs while loop in Python
  • Python for loop index

In this Python tutorial, we have discussed the Python While loop continue. Here we have also covered the following examples:

  • Python while loop continue break
  • Python while loop exception continue
  • Python nested while loop continue
  • Python while true loop continue
  • While loop continue python example
  • Python continue while loop after exception
  • Python try except continue while loop
  • Python while loop break and continue

Bijay Kumar MVP

Python is one of the most popular languages in the United States of America. I have been working with Python for a long time and I have expertise in working with various libraries on Tkinter, Pandas, NumPy, Turtle, Django, Matplotlib, Tensorflow, Scipy, Scikit-Learn, etc… I have experience in working with various clients in countries like United States, Canada, United Kingdom, Australia, New Zealand, etc. Check out my profile.

In Python programming, exception handling allows a programmer to enable flow control. And it has no. of built-in exceptions to catch errors in case your code breaks. Using try-except is the most common and natural way of handling unexpected errors along with many more exception handling constructs. In this tutorial, you’ll get to explore some of the best techniques to use try-except in Python.

Error Handling or Exception Handling in Python can be enforced by setting up exceptions. Using a try block, you can implement an exception and handle the error inside an except block. Whenever the code breaks inside a try block, the regular code flow will stop and the control will get switched to the except block for handling the error.

Why use Try-Except/Try-Except-else Clause? With the help of try-except and try-except-else, you can avoid many unknown problems that could arise from your code. For example, the Python code using LBYL (Look before you leap) style can lead to race conditions. Here, the try-except clause can come to rescue you. Also, there are cases where your code depends critically on some information which could get outdated till the time you receive it. For example, the code making calls to os.path.exists or Queue.full may fail as these functions might return data that become stale by the time you use it. The wiser choice here would be to follow the try-except-else style in your code to manage the above cases more reliably.

Raising exceptions is also permissible in Python. It means you can throw or raise an exception whenever it is needed. You can do it simply by calling [raise Exception(‘Test error!’)] from your code. Once raised, the exception will stop the current execution as usual and will go further up in the call stack until handled.

Why use Exceptions? They not only help solve popular problems like race conditions but are also very useful in controlling errors in areas like loops, file handling, database communication, network access and so on.

Hence, we’ll cover broader problems and provide solutions in this post. Please note that exception handling is an art which brings you immense powers to write robust and quality code. So, brace to read some keynotes on exceptions along with the best ways to handle them.

Must Read – Everything You Should Know About Python Copy File [Python File I/O].

Python: Tips to Use Try-Except, Try-Except-Else, and More

How to Best Use Try-Except in Python

How to Best Use Try-Except in Python
  • How to handle an arbitrary exception
  • Catch multiple exceptions in one except block
  • Handling multiple exceptions with one except block
  • Re-raising exceptions in Python
  • When to use the else clause
  • Make use of [finally clause]
  • Use the As keyword to catch specific exception types
  • Best practice for manually raising exceptions
  • How to skip through errors and continue execution
  • Most common exception errors in Python
  • Examples of most common exceptions in Python

1. How to handle an arbitrary exception

Sometimes, you may need a way to allow any arbitrary exception and also want to be able to display the error or exception message.

It is easily achievable using the Python exceptions. Check the below code. While testing, you can place the code inside the try block in the below example.

try:
    #your code
except Exception as ex:
    print(ex)

Back to top

2. Catch multiple exceptions in one except block

You can catch multiple exceptions in a single except block. See the below example.

except (Exception1, Exception2) as e:
    pass

Please note that you can separate the exceptions from the variable with a comma which is applicable in Python 2.6/2.7. But you can’t do it in Python 3. So, you should prefer to use the [as] keyword.

Back to top

3. Handling multiple exceptions with one except block

There are many ways to handle multiple exceptions. The first of them requires placing all the exceptions which are likely to occur in the form of a tuple. Please see from below.

try:
    file = open('input-file', 'open mode')
except (IOError, EOFError) as e:
    print("Testing multiple exceptions. {}".format(e.args[-1]))

The next method is to handle each exception in a dedicated except block. You can add as many except blocks as needed. See the below example.

try:
    file = open('input-file', 'open mode')
except EOFError as ex:
    print("Caught the EOF error.")
    raise ex
except IOError as e:
    print("Caught the I/O error.")
    raise ex

The last but not the least is to use the except without mentioning any exception attribute.

try:
    file = open('input-file', 'open mode')
except:
    # In case of any unhandled error, throw it away
    raise

This method can be useful if you don’t have any clue about the exception possibly thrown by your program.

Back to top

4. Re-raising exceptions in Python

Exceptions once raised keep moving up to the calling methods until handled. Though you can add an except clause which could just have a [raise] call without any argument. It’ll result in reraising the exception.

See the below example code.

try:
    # Intentionally raise an exception.
    raise Exception('I learn Python!')
except:
    print("Entered in except.")
    # Re-raise the exception.
    raise

Output:

Entered in except.
Traceback (most recent call last):
  File "python", line 3, in <module>
Exception: I learn Python!

Back to top

5. When to use the else clause

Use an else clause right after the try-except block. The else clause will get hit only if no exception is thrown. The else statement should always precede the except blocks.

In else blocks, you can add code which you wish to run when no errors occurred.

See the below example. In this sample, you can see a while loop running infinitely. The code is asking for user input and then parsing it using the built-in [int()] function. If the user enters a zero value, then the except block will get hit. Otherwise, the code will flow through the else block.

while True:
    # Enter integer value from the console.
    x = int(input())

    # Divide 1 by x to test error cases
    try:
        result = 1 / x
    except:
        print("Error case")
        exit(0)
    else:
        print("Pass case")
        exit(1)

Back to top

6. Make use of [finally clause]

If you have a code which you want to run in all situations, then write it inside the [finally block]. Python will always run the instructions coded in the [finally block]. It is the most common way of doing clean up tasks. You can also make sure the clean up gets through.

An error is caught by the try clause. After the code in the except block gets executed, the instructions in the [finally clause] would run.

Please note that a [finally block] will ALWAYS run, even if you’ve returned ahead of it.

See the below example.

try:
    # Intentionally raise an error.
    x = 1 / 0
except:
    # Except clause:
    print("Error occurred")
finally:
    # Finally clause:
    print("The [finally clause] is hit")

Output:

Error occurred
The [finally clause] is hit

Back to top

7. Use the As keyword to catch specific exception types

With the help of as <identifier>, you can create a new object. And you can also the exception object. Here, the below example, we are creating the IOError object and then using it within the clause.

try:
    # Intentionally raise an error.
    f = open("no-file")
except IOError as err:
    # Creating IOError instance for book keeping.
    print("Error:", err)
    print("Code:", err.errno)

Output:

('Error:', IOError(2, 'No such file or directory'))
('Code:', 2)

Back to top

8. Best practice for manually raising exceptions

Avoid raising generic exceptions because if you do so, then all other more specific exceptions have to be caught also. Hence, the best practice is to raise the most specific exception close to your problem.

Bad example.

def bad_exception():
    try:
        raise ValueError('Intentional - do not want this to get caught')
        raise Exception('Exception to be handled')
    except Exception as error:
        print('Inside the except block: ' + repr(error))
        
bad_exception()

Output:

Inside the except block: ValueError('Intentional - do not want this to get caught',)

Best Practice:

Here, we are raising a specific type of exception, not a generic one. And we are also using the args option to print the incorrect arguments if there is any. Let’s see the below example.

try:
    raise ValueError('Testing exceptions: The input is in incorrect order', 'one', 'two', 'four') 
except ValueError as err:
    print(err.args)

Output:

('Testing exceptions: The input is in incorrect order', 'one', 'two', 'four')

Back to top

9. How to skip through errors and continue execution

Ideally, you shouldn’t be doing this. But if you still want to do, then follow the below code to check out the right approach.

try:
    assert False
except AssertionError:
    pass
print('Welcome to Prometheus!!!')

Output:

Welcome to Prometheus!!!

Back to top

Now, have a look at some of the most common Python exceptions and their examples.

Most common exception errors

  • IOError – It occurs on errors like a file fails to open.
  • ImportError – If a python module can’t be loaded or located.
  • ValueError – It occurs if a function gets an argument of right type but an inappropriate value.
  • KeyboardInterrupt – It gets hit when the user enters the interrupt key (i.e. Control-C or Del key)
  • EOFError – It gets raised if the input functions (input()/raw_input()) hit an end-of-file condition (EOF) but without reading any data.

Back to top

Examples of most common exceptions

except IOError:
print('Error occurred while opening the file.')

except ValueError:
print('Non-numeric input detected.')

except ImportError:
print('Unable to locate the module.')

except EOFError:
print('Identified EOF error.')

except KeyboardInterrupt:
print('Wrong keyboard input.')

except:
print('An error occurred.')

Back to top

while programming, errors are bound to happen. It’s a fact which no one can ignore. And there could be many reasons for errors like bad user input, insufficient file permission, the unavailability of a network resource, insufficient memory or most likely the programmer’s mistake.

Anyways, all of this can be handled if your code use exception handling and implement it with constructs like try-except, or tr-except-else, try-except-finally. Hope, you would have enjoyed reading the above tutorial.

If you liked the post, then please don’t miss to share it with friends and on social media (facebook/twitter).

Best,
TechBeamers.

  1. Use the try-except Statement With continue to Skip Iterations in a Python Loop
  2. Use the if-else Statement With continue to Skip Iterations in a Python Loop

Skip Iterations in a Python Loop

This article explains different ways to skip the specific iterations of a loop in Python.

Sometimes, we have to deal with the requirements of performing some tasks repeatedly while skipping a few of them in between. For example, when you are running a loop and want to skip the part of that iteration that can throw an exception.

Use the try-except Statement With continue to Skip Iterations in a Python Loop

In Python, exceptions can be easily handled through a try-except statement. If you think that you may come across some exceptions during loop iterations, due to which the execution of the loop may stop, then you can use this statement.

List_A=[25, 30, 100, 600]
List_B= [5, 10, 0, 30]
Result=[]
for i, dividend in enumerate(List_A):
    try:
      # perform the task
      Result.append(dividend/List_B[i])
    except:
      # handle the exceptions
      continue
print(Result)

In the above code, we have two lists, and we want to divide List_A by List_B element by element.

In Python, when you divide a number by zero, the ZeroDivisionError occurs. Since List_B contains zero as a divisor, division by it will generate this error during loop execution.

So to avoid this error, we use the except block. The exception will be raised when the error occurs, and the except block will be executed.

The continue statement ignores any subsequent statements in the current loop iteration and returns to the top of the loop. This is how you can skip the loop iterations.

The above code generates the following output:

Use the if-else Statement With continue to Skip Iterations in a Python Loop

We can do the same task with an if-else statement and continue.

List_A=[25, 30, 100, 600]
List_B= [5, 10, 0, 30]
Result=[]
for i, dividend in enumerate(List_A):
  if List_B[i]!=0:
    Result.append(dividend/List_B[i])
  else:
    continue
print(Result)

This is a straightforward code. The difference between this solution and the try-except solution is that the former implementation already knows the condition for which the loop execution may get stopped.

Therefore, this condition can be explicitly coded to skip that iteration.

Output:

As a result of the above implementations, you can skip loop iteration on which error/exception may occur without the loop being halted.

Сделайте while True внутри цикла for, поместите код try внутри и перерыв в этом цикле while только тогда, когда ваш код преуспеет.

for i in range(0,100):
    while True:
        try:
            # do stuff
        except SomeSpecificException:
            continue
        break

zneak
18 янв. 2010, в 06:57

Поделиться

Я предпочитаю ограничивать количество повторений, так что, если есть проблема с этим конкретным элементом, вы, в конце концов, перейдете к следующему:

for i in range(100):
  for attempt in range(10):
    try:
      # do thing
    except:
      # perhaps reconnect, etc.
    else:
      break
  else:
    # we failed all the attempts - deal with the consequences.

xorsyst
05 окт. 2011, в 15:08

Поделиться

Пакет повторных попыток — это хороший способ повторить блок кода при ошибке.

Например:

@retry(wait_random_min=1000, wait_random_max=2000)
def wait_random_1_to_2_s():
    print("Randomly wait 1 to 2 seconds between retries")

goneri
18 сен. 2014, в 13:48

Поделиться

Вот решение, подобное другим, но оно приведет к возникновению исключения, если ему не удастся выполнить заданное число или повторить попытку.

tries = 3
for i in range(tries):
    try:
        do_the_thing()
    except KeyError as e:
        if i < tries - 1: # i is zero indexed
            continue
        else:
            raise
    break

TheHerk
19 янв. 2016, в 21:27

Поделиться

Более «функциональный» подход без использования этих уродливых циклов while:

def tryAgain(retries=0):
    if retries > 10: return
    try:
        # Do stuff
    except:
        retries+=1
        tryAgain(retries)

tryAgain()

restbeckett
28 окт. 2010, в 21:51

Поделиться

Самый ясный способ — явно установить i. Например:

i = 0
while i < 100:
    i += 1
    try:
        # do stuff

    except MyException:
        continue

Tomi Kyöstilä
18 янв. 2010, в 06:18

Поделиться

Общее решение с тайм-аутом:

import time

def onerror_retry(exception, callback, timeout=2, timedelta=.1):
    end_time = time.time() + timeout
    while True:
        try:
            yield callback()
            break
        except exception:
            if time.time() > end_time:
                raise
            elif timedelta > 0:
                time.sleep(timedelta)

Использование:

for retry in onerror_retry(SomeSpecificException, do_stuff):
    retry()

Laurent LAPORTE
04 дек. 2014, в 19:25

Поделиться

Использование рекурсии

for i in range(100):
    def do():
        try:
            ## Network related scripts
        except SpecificException as ex:
            do()
    do() ## invoke do() whenever required inside this loop

Joseph Thomas
31 авг. 2016, в 12:31

Поделиться

В библиотеке Python Decorator есть нечто похожее.

Пожалуйста, имейте в виду, что это не проверка исключений, а возвращаемое значение. Повторяется до тех пор, пока оформленная функция не вернет True.

Немного измененная версия должна сделать свое дело.

Michael
15 июнь 2011, в 08:41

Поделиться

Вы можете использовать пакет повторной проверки Python.
Retrying

Это написано на Python, чтобы упростить задачу добавления поведения повтора к чему угодно.

ManJan
18 окт. 2017, в 17:54

Поделиться

Использование while и счетчика:

count = 1
while count <= 3:  # try 3 times
    try:
        # do_the_logic()
        break
    except SomeSpecificException as e:
        # If trying 3rd time and still error?? 
        # Just throw the error- we don't have anything to hide :)
        if count == 3:
            raise
        count += 1

Ranju R
31 авг. 2016, в 13:24

Поделиться

Если вы хотите найти решение без вложенных циклов и использования break при успехе, вы можете разработать быструю retriable для любой итерации. Вот пример сетевой проблемы, с которой я часто сталкиваюсь — срок сохраненной аутентификации истекает. Использование этого будет читать так:

client = get_client()
smart_loop = retriable(list_of_values):

for value in smart_loop:
    try:
        client.do_something_with(value)
    except ClientAuthExpired:
        client = get_client()
        smart_loop.retry()
        continue
    except NetworkTimeout:
        smart_loop.retry()
        continue

Mikhail
24 июль 2018, в 21:30

Поделиться

for _ in range(5):
    try:
        # replace this with something that may fail
        raise ValueError("foo")

    # replace Exception with a more specific exception
    except Exception as e:
        err = e
        continue

    # no exception, continue remainder of code
    else:
        break

# did not break the for loop, therefore all attempts
# raised an exception
else:
    raise err

Моя версия похожа на несколько выше, но не использует отдельный во while цикла, и вновь поднимает последнее исключение, если все повторные попытки терпят неудачу. Можно явно установить err = None наверху, но это не является строго необходимым, поскольку он должен выполнять только последний блок else если произошла ошибка и, следовательно, установлен err.

n8henrie
05 фев. 2019, в 16:26

Поделиться

Я использую следующие в моих кодах,

   for i in range(0, 10):
    try:
        #things I need to do
    except ValueError:
        print("Try #{} failed with ValueError: Sleeping for 2 secs before next try:".format(i))
        time.sleep(2)
        continue
    break

H S Rathore
21 нояб. 2018, в 07:52

Поделиться

Вот моя идея о том, как это исправить:

j = 19
def calc(y):
    global j
    try:
        j = j + 8 - y
        x = int(y/j)   # this will eventually raise DIV/0 when j=0
        print("i = ", str(y), " j = ", str(j), " x = ", str(x))
    except:
        j = j + 1   # when the exception happens, increment "j" and retry
        calc(y)
for i in range(50):
    calc(i)

Amine
24 дек. 2015, в 17:45

Поделиться

увеличивает вашу переменную цикла только тогда, когда предложение try успешно

appusajeev
18 янв. 2010, в 11:12

Поделиться

Ещё вопросы

  • 0угловая форма представить получить действие добавить ключ-пара значений
  • 0Вопрос для начинающих о XML и XSLT
  • 0Symfony2 как получить диспетчер сущностей в Listener
  • 1Создание объекта с помощью отражения с анонимным типом
  • 0дата форматирования от контроллера не получает ожидаемый результат
  • 1Discord.py как проверить, есть ли у ввода десятичное число
  • 0Отображение данных JSON в <Select> с помощью AngularJS (ошибка)
  • 1Идентификация дочернего класса, вызывающего статическую функцию базового класса
  • 0Как скопировать файл из одного каталога в другой, используя переменные и массивы для каталогов и файлов в php?
  • 1Dropzonejs вызывает ошибку и отменяет загрузку
  • 0Как исправить ошибки параметров в PHP?
  • 1Bubble sort на 2D Array Java
  • 0Невозможно заставить редактор Angular в плагине Eclipse AngularJS работать должным образом
  • 1Кнопка JS не обновляет innerhtml
  • 1C # Использование интерфейса для доступа к методам
  • 0Перехватчик с ограниченным ответом для заголовков
  • 0Используя область родительского div
  • 0tabSlideOut — вызвать клик
  • 0JQuery / JavaScript исчезают в каждом элементе?
  • 0Qt: QVector <bool> to QByteArray
  • 1Подчеркивание: потеря ссылки на массив объекта
  • 1Maven выбирает неправильную дубликатную зависимость
  • 0Проблемы с реализацией итератора двусвязного списка
  • 1Определить свойство привязки, измененное в пользовательском элементе управления
  • 1Написать результат функции в CSV
  • 1ошибка в Android 2.1 XML Drawables?
  • 1Как предотвратить растяжение TextView его родительского LinearLayout?
  • 1Как конвертировать String в DateFormat в Java?
  • 1создать исполняемый файл из программы на Python с зависимостями
  • 1Однострочная короткая форма для функции без стрелки?
  • 0Блокировка JDBC: как определить, что исключение вызвано таймаутом блокировки?
  • 0Как сделать несколько запросов в Spring Batch (в частности, используйте LAST_INSERT_ID ())
  • 0Однократная инициализация переменной в cocos2d-x
  • 0скольжение элементов на странице с помощью jquery
  • 0Jquery гармошка не разрушается
  • 0Загрузите HTML-страницу в фоновом режиме с помощью внедрения JavaScript
  • 1Почему InitializeComponent (); недоступен из-за уровня защиты?
  • 0не может получить доступ к закрытому члену, объявленному в классе ‘Windows :: Devices :: Sensors :: Accelerometer’
  • 0Приложение MeanJS не может создать модуль AngularJS после нажатия
  • 1Класс Singleton создает исключение System.TypeInitializationException
  • 0Angular ui-router Вложенные состояния открываются из URL
  • 1Разделите одну строку на две, используя string.split java [duplicate]
  • 0При наведении курсора на меню навигации все, что находится внизу, сдвигается вниз, но мне нужно, чтобы оно просто оставалось над тем, что под ним, а не опускало его вниз.
  • 0php mysql — вставить один запрос из цикла while
  • 0Как объединить несколько частичек через templateUrl AngularJS
  • 0Ошибка типа: jQuery.colorbox не определен
  • 1Количество задач в очереди; как я могу избежать глобальной переменной?
  • 1Динамический импорт Python3 с exec — почему «as» не выполняется?
  • 0Сервер контактной формы начальной загрузки не отвечает

Понравилась статья? Поделить с друзьями:
  • Pxe e99 unexpected network error
  • Python check syntax error
  • Pxe e63 error while initializing the nic
  • Pxe e61 как исправить
  • Pxe e53 no boot filename received как исправить