![](/img/trans.png)
[英]how to continue program execution in Python continue after exception/error
[英]Continue After Exception - Python
我试图在我的代码中使用try
和except
块来捕获错误,然后让它休眠 5 秒钟,然后我想从它停止的地方继续。 以下是我的代码,目前一旦它捕获异常,它就不会继续并在异常后停止。
from botocore.exceptions import ClientError
tries = 0
try:
for pag_num, page in enumerate(one_submitted_jobs):
if 'NextToken' in page:
print("Token:",pag_num)
else:
print("No Token in page:", pag_num)
except ClientError as exception_obj:
if exception_obj.response['Error']['Code'] == 'ThrottlingException':
print("Throttling Exception Occured.")
print("Retrying.....")
print("Attempt No.: " + str(tries))
time.sleep(5)
tries +=1
else:
raise
异常后如何使其继续? 任何帮助都会很棒。
注意 - 我试图在我的代码中捕获 AWS 的ThrottlingException
错误。
以下代码用于向@Selcuk 演示,以显示我目前从他的回答中得到的信息。 一旦我们同意我的操作是否正确,以下内容将被删除。
tries = 1
pag_num = 0
# Only needed if one_submitted_jobs is not an iterator:
one_submitted_jobs = iter(one_submitted_jobs)
while True:
try:
page = next(one_submitted_jobs)
# do things
if 'NextToken' in page:
print("Token: ", pag_num)
else:
print("No Token in page:", pag_num)
pag_num += 1
except StopIteration:
break
except ClientError as exception_obj:
# Sleep if we are being throttled
if exception_obj.response['Error']['Code'] == 'ThrottlingException':
print("Throttling Exception Occured.")
print("Retrying.....")
print("Attempt No.: " + str(tries))
time.sleep(3)
tries +=1
您无法继续运行,因为您的for
行中发生了异常。 这有点棘手,因为在这种情况下, for
语句无法知道是否还有更多项目要处理。
一种解决方法可能是改用while
循环:
pag_num = 0
# Only needed if one_submitted_jobs is not an iterator:
one_submitted_jobs = iter(one_submitted_jobs)
while True:
try:
page = next(one_submitted_jobs)
# do things
pag_num += 1
except StopIteration:
break
except ClientError as exception_obj:
# Sleep if we are being throttled
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.