# phone num
try:
phone=soup.find("div", "phone-content")
for a in phone:
phone_result= str(a).get_text().strip().encode("utf-8")
print "Phone information:", phone_result
except ValueError:
phone_result="Error"
出现uni-code错误时,我的程序停止了,但我想使用try来避免终止程序。我该怎么做?
我收到不同类型的错误。我想要无论错误如何都不会终止循环的东西。我只是想跳过有错误的循环部分
通过使用
try:
...
except:
...
您总是可以在try块尝试中捕获每个错误。但问题是,你会赶上甚至KeyboardInterrupt
和SystemExit
但是,最好捕获准备处理的错误,以免隐藏错误。
try:
...
except UnicodeError as e:
handle(e)
至少,您至少应该像捕获一样具体StandardError
。
使用您的代码演示:
try:
phone=soup.find("div", "phone-content")
for a in phone:
phone_result= str(a).get_text().strip().encode("utf-8")
print "Phone information:", phone_result
except StandardError as e:
phone_result="Error was {0}".format(e)
请参阅“异常层次结构”以帮助您评估错误处理的特殊性。http://docs.python.org/2/library/exceptions.html#exception-hierarchy
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句