【发布时间】:2021-06-20 19:14:45
【问题描述】:
我试图在我的代码中使用 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循环?在这种情况下,您应该将try放在for里面,而不是在外面。 -
@Selcuk 是的,执行 for 循环。我尝试了这里提到的 for 循环 SO link ,在这种情况下,它不会捕获执行
-
这没有任何意义。在这种情况下,您应该在
for行中得到异常。one_submitted_jobs是什么?是发电机吗? -
您应该使用任何迭代来使其循环工作,但是当您调用引发异常时,它会强制您停止循环。
-
@Selcuk 是的,
one_submitted_jobs是一个生成器,我在for循环中遇到错误。不知道如何继续
标签: python-3.x exception try-catch