[英]Try running code x times and if it fails x times raise exception
There is a code that randomly raises an error.有一个随机引发错误的代码。
When the code fails, I want to rerun it, but if it fails x times I want to raise a custom error.当代码失败时,我想重新运行它,但如果它失败 x 次,我想引发一个自定义错误。
Is there a proper way to do it in Python?在 Python 中是否有适当的方法来做到这一点?
I am thinking the following but it doesn't seem to be the best.我正在考虑以下内容,但它似乎不是最好的。
class MyException(Exception): pass try: for i in range(x): try: some_code() break except: pass except: raise MyException("Check smth")
You can do it like this你可以这样做
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")
Just create an infinite loop that will break on success, and count the errors in the except
block:只需创建一个将在成功时中断的无限循环,并计算
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
Another way to do it:另一种方法:
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.