首页 > 解决方案 > 异常后继续 - Python

问题描述

我试图在我的代码中阻止tryexcept阻止错误,然后让它休眠 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

异常后如何使其继续?任何帮助都会很棒。

注意 - 我试图ThrottlingException在我的代码中捕捉 AWS 的错误。

以下代码用于向@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 

标签: python-3.xexceptiontry-catch

解决方案


您无法继续运行,因为您的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

推荐阅读