【问题标题】:Continue After Exception - Python异常后继续 - Python
【发布时间】:2021-06-20 19:14:45
【问题描述】:

我试图在我的代码中使用 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

我怎样才能让它在异常后继续?任何帮助都会很棒。

注意 - 我试图在我的代码中捕获 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


【解决方案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

【讨论】:

  • 感谢您的时间,但是,当我这样做时,它仍然会在发现第一个客户端错误异常后停止。我现在一无所知:(
  • 停下来做什么?它会脱离while 循环吗?
  • 我想用你的方法,我们已经很接近了。唯一的事情是一旦except ClientError as exception_obj 发生,我们仍然需要继续,直到我们遍历了生成器/迭代器中的所有对象。截至目前,在客户端异常之后,while 循环中断并且什么都不做只是停止执行。
  • 没有什么可以打破except ClientError... 块中的循环。你确定你正在执行ThrottlingException 子句而不是else 部分吗?
  • 我确信我做了你让我做的事。我发布了我的代码供您参考。请有空的时候看看并给我评论。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-10-29
  • 1970-01-01
  • 2014-12-18
  • 2021-05-13
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多