有一个代码随机引发错误。
当代码失败时,我想重新运行它,但如果它失败了x次,我想引发一个自定义错误。
在Python中有合适的方法吗?
#我在想以下几点,但似乎不是最好的。
class MyException(Exception):
pass
try:
for i in range(x):
try:
some_code()
break
except:
pass
except:
raise MyException("Check smth")
只需创建一个在成功时中断的无限循环,并计算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
你可以这样做
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")