无论Python中出现错误如何重新启动迭代[重复]

问题描述 投票:0回答:1

我的代码会产生很多错误,导致它跳出循环。这些错误是由于此代码中的编码问题或远程服务器问题造成的。无论错误是什么,是否都可以重新启动代码块。我所想的是 while 循环内的 while 循环,但由于某种原因它仍然打破了迭代。

while True:
     while True:
         [CODE BLOCK]

您能否告知如何强制代码块重新启动迭代,无论出现错误如何。如果有任何错误,请跳过并继续。

python python-3.x iteration
1个回答
1
投票
while True:
    try:
        while True:
            try:
                # Your code block that might raise an error
                # ...
                
            except Exception as e:
                # Handle the error if needed
                print(f"An error occurred in inner loop: {e}")
            
            finally:
                # This block will always execute, allowing you to restart the inner loop
                print("Restarting inner loop...")
            
    except KeyboardInterrupt:
        # Allow the user to stop the process by pressing Ctrl+C
        print("Process stopped by user.")
        break
    
    except Exception as e:
        # Handle other exceptions that might occur in the outer loop
        print(f"An error occurred in outer loop: {e}")

无论内循环是否发生错误,外层 while True 循环都会不断重新启动内循环。

请记住,如果错误不断重复发生,使用这样的结构可能会导致无限循环。进行适当的错误处理并可能添加条件以在一定次数的重试后或满足特定条件后打破循环非常重要。

© www.soinside.com 2019 - 2024. All rights reserved.