如何在异常处理后回到for循环 [英] How to get back to the for loop after exception handling
问题描述
我准备运行这段代码,但在我想修复异常处理之前:
for l in bios:
pre>
OpenThisLink = url + l
try:
response = urllib2.urlopen(OpenThisLink)
除了urllib2.HTTPError:
pass
bio = response.read )
item = re.search('(JD)(。*?)(\d +)',bio)
....
根据建议这里,我添加了
try ...除了
,但现在如果一个页面没有打开我得到这个错误:bio = response.read()
NameError:name'response'未定义
所以程序继续执行。相反,我希望它回到for循环并尝试下一个url。我试过
break
而不是pass
,但是结束了程序。任何建议?解决方案使用
continue
而不是break
。
语句
pass
是一个no-op(意思是它没有做任何事情)。程序只是继续下一个语句,这就是为什么你收到错误。
break
退出循环在循环后立即继续运行下一条语句。在这种情况下,没有更多的语句,这就是程序终止的原因。
继续
重新启动循环,与下一个项目。这正是你想要的。I am ready to run this code but before I want to fix the exception handling:
for l in bios: OpenThisLink = url + l try: response = urllib2.urlopen(OpenThisLink) except urllib2.HTTPError: pass bio = response.read() item = re.search('(JD)(.*?)(\d+)', bio) ....
As suggested here, I added the
try...except
but now if a page doesn't open I get this error:bio = response.read() NameError: name 'response' is not defined
So the program continues to execute. Instead I want it to go back to the for loop and try the next url. I tried
break
instead ofpass
but that ends the program. Any suggestions?解决方案Use
continue
instead ofbreak
.The statement
pass
is a no-op (meaning that it doesn't do anything). The program just continues to the next statement, which is why you get an error.
break
exits the loops and continues running from the next statement immediately after the loop. In this case, there are no more statements, which is why your program terminates.
continue
restarts the loop but with the next item. This is exactly what you want.这篇关于如何在异常处理后回到for循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!