繁体   English   中英

尝试添加错误处理机制时出现“继续不在循环中”错误

[英]'continue not in loop' error while trying to add an error handling mechanism

我一直在尝试向我的代码部分添加错误处理机制。 但是,当它运行时,它说“在循环外继续”,但查看代码它应该在 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   

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
    ...

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

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

任何一个:

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 ,就像您的情况一样。)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM