如何解决尝试添加错误处理机制时出现“ Continue not in 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
是专门,用于立即移至for
或while
循环的下一个迭代;这不是通用的“移至下一个语句”指令。
在try
/ except
语句中,只要到达try
,except
,else
或finally
块的末尾,则执行从下一个complete语句而不是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
。)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。