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_countandlast_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_trackerkeeps 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
相关产品推荐
相关产品推荐

