You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python中同一错误重复3次时如何终止while True循环?

Exit while True Loop on 3 Occurrences of the Same Error in Python

Hey there! Let's tackle this problem—exiting a while True loop when the same error pops up 3 times. There are two common scenarios you might care about: consecutive same errors (back-to-back failures of the same type) or total occurrences of the same error (even if other errors happen in between). Here's how to handle both:

Scenario 1: Exit on 3 Consecutive Same Errors

Use this if you want to stop the loop only when the exact same error happens three times in a row (successful runs or different errors reset the count):

# Initialize tracking variables
error_count = 0
last_exception_type = None

while True:
    try:
        # Replace this with your actual code that might raise errors
        # Example: Simulate random errors for demonstration
        import random
        if random.random() < 0.6:
            raise ValueError("Invalid input value")
        elif random.random() < 0.8:
            raise TypeError("Incorrect data type")
        else:
            print("Code executed successfully!")
            
        # Reset counter if code runs without errors
        error_count = 0
        last_exception_type = None

    except Exception as e:
        current_exc_type = type(e)
        
        # Update error count based on whether it's the same error as last time
        if current_exc_type == last_exception_type:
            error_count += 1
        else:
            error_count = 1
            last_exception_type = current_exc_type
        
        # Optional: Print error details for debugging
        print(f"Error encountered: {str(e)} | Consecutive count: {error_count}")
        
        # Exit loop when consecutive same errors hit 3
        if error_count >= 3:
            print("Same error occurred 3 times consecutively—exiting loop.")
            break

Key Details:

  • We track both the count of consecutive errors and the type of the last error using error_count and last_exception_type.
  • If the code runs successfully, we reset the counter entirely—since a successful execution breaks the streak of errors.
  • We use type(e) to compare exception types, which ensures we're matching exact error classes (not just error messages).

Scenario 2: Exit on 3 Total Occurrences of the Same Error

Use this if you want to stop the loop when a specific error type has happened 3 times in total, regardless of other errors or successful runs in between:

# Use a dictionary to track total occurrences of each error type
error_tracker = {}

while True:
    try:
        # Replace with your actual code
        import random
        if random.random() < 0.6:
            raise ValueError("Invalid input value")
        elif random.random() < 0.8:
            raise TypeError("Incorrect data type")
        else:
            print("Code executed successfully!")

    except Exception as e:
        exc_type = type(e)
        # Update the count for this error type
        error_tracker[exc_type] = error_tracker.get(exc_type, 0) + 1
        
        # Optional: Print error details
        print(f"Error encountered: {str(e)} | Total occurrences: {error_tracker[exc_type]}")
        
        # Exit loop when any error type hits 3 total occurrences
        if error_tracker[exc_type] >= 3:
            print(f"This error has occurred 3 times total—exiting loop.")
            break

Key Details:

  • A dictionary error_tracker keeps a running total for each exception type.
  • Even if other errors or successful runs happen in between, the count for each error type persists.
  • You can adjust this to target only specific error types (e.g., only track ValueError) by adding a check in the except block.

内容的提问来源于stack exchange,提问作者skw0314

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.11 08:27:54