'continue not in loop' 尝试添加错误处理机制时出错

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

我一直在尝试向我的代码部分添加错误处理机制。然而,当它运行时它说 'continue outside of loop' 但查看代码它应该在 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 循环的下一次迭代;它不是 all-purpose move-to-the-next-statement 指令。

try/except 语句中,任何时候到达 tryexceptelse 或 [=19= 的末尾] 块,执行继续下一个完整的语句,而不是 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,如您的情况。)