【发布时间】: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。