尝试运行代码x次,如果失败x次,则会引发异常

时间:2020-05-03 14:15:10

标签: python try-catch

有一个代码会随机产生一个错误。

当代码失败时,我想重新运行它,但是如果失败了x次,我会引发自定义错误。

在Python中有正确的方法吗?

我在想以下内容,但这似乎不是最好的。

class MyException(Exception):
    pass


try:
    for i in range(x):
        try:
            some_code()
            break
        except:
            pass
except:
    raise MyException("Check smth")

2 个答案:

答案 0 :(得分:0)

您可以这样做

for i in range(x):
    retries = <how many times you want to try> 
    while retries: # This could be while 1 since the loop will end in successful run or with exception when retries run out. 
        try:
            some code
            break # End while loop when no errors
         except:
            retries =- 1
            if not retries:
                raise MyException("Check smth")

答案 1 :(得分:0)

只需创建一个无限循环,该循环将在成功后中断,并计算except块中的错误:

max_errors = 7

errors = 0
while True:
    try:
        run_code()
        break
    except ExceptionYouWantToCatch:  # You shouldn't use a bare except:
        errors += 1
        if errors > max_errors:
            raise MyException

另一种方法:

max_errors = 7


for run in range(max_errors):
    try:
        run_code()
        break
    except ExceptionYouWantToCatch:  # You shouldn't use a bare except:
        pass
else:  # will run if we didn't break out of the loop, so only failures
    raise MyException
相关问题