【问题标题】:'continue not in loop' error while trying to add an error handling mechanism尝试添加错误处理机制时出现“继续不在循环”错误
【发布时间】:2021-01-02 05:35:15
【问题描述】:

我一直在尝试向我的代码部分添加错误处理机制。但是,当它运行时,它会说“在循环外继续”,但查看代码它应该在 try 循环内。怎么了?

def download_media_item(self, entry):
    try:
        url, path = entry
        # Get the file extension example: ".jpg"
        ext = url[url.rfind('.'):]
        if not os.path.isfile(path + ext):
            r = requests.get(url, headers=headers, timeout=15)
            if r.status_code == 200:
                open(path + ext, 'wb').write(r.content)
                self.user_log.info('File {} downloaded from {}'.format(path, url))
                return True
            elif r.status_code == 443:
                print('------------the server reported a 443 error-----------')
                return False
        else:
            self.user_log.info('File {} already exists. URL: {}'.format(path, url))
            return False
    except requests.ConnectionError:
        print("Received ConnectionError. Retrying...")
        continue
    except requests.exceptions.ReadTimeout:
        print("Received ReadTimeout. Retrying...")
        continue   

【问题讨论】:

  • 你没有for循环。
  • 您的continue 语句不在任何循环内。你是说某处有一个for 循环吗?
  • 什么for 循环? except 案例中的两个 continue 语句都在循环之外
  • 您不需要continue 来继续执行try 语句;这已经发生了。例如,从 except requests.ConnectionError 中省略 continue 不会导致接下来执行 except requests.exceptions.ReadTimeout 块。
  • 做不做,没有try loop

标签: python loops except


【解决方案1】:

continue 专门用于立即移动到forwhile 循环的下一次迭代;它不是一个通用的移动到下一条语句的指令。

try/except 语句中,只要您到达tryexceptelsefinally 块的末尾,就会继续执行下一个完整语句,而不是下一个try 语句的一部分。

def download_media_item(self, entry):
    # 1: try statement
    try:
        ...
        # If you get here, execution goes to #2 below, not the
        # except block below
    except requests.ConnectionError:
        print("Received ConnectionError. Retrying...")
        # Execution goes to #2 below, not the except block below
    except requests.exceptions.ReadTimeout:
        print("Received ReadTimeout. Retrying...")
        # Execution goes to #2 below

    # 2: next statement
    ...

【讨论】:

    【解决方案2】:

    看来您实际上想要做的是继续循环,直到没有引发异常。

    通常,您可以通过在成功完成的情况下中断无限循环来做到这一点。

    要么:

    while True:
        try:
            # do stuff
        except requests.ConnectionError:
            # handle error
            continue
        except requests.exceptions.ReadTimeout:
            # handle error
            continue
        break
    

    或者:

    while True:
        try:
            # do stuff
        except requests.ConnectionError:
            # handle error
        except requests.exceptions.ReadTimeout:
            # handle error
        else:
            break
    

    但是,在这种情况下,“做事”似乎总是以到达 return 语句结束,因此不需要 break,以下简化版本就足够了:

    while True:
        try:
            # do stuff
            return some_value
        except requests.ConnectionError:
            # handle error
        except requests.exceptions.ReadTimeout:
            # handle error
    

    (此处显示的单个return 可能指的是替代控制流,所有这些都导致return,就像您的情况一样。)

    【讨论】:

    • 我认为 OP 不需要任何 break,特别是因为如果没有例外,他们当前的代码似乎总是有 return 路径。无论如何,这是我的 +1。
    • @quamrana 好点,谢谢。在这种情况下,我没有仔细研究“做事”的细节。我会将您的观察作为注释添加到最后,但就可能的更通用用途而言,我想我会按原样保留答案。
    • @quamrana 现在更新以反映这一点。再次感谢您的观察。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-01-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多