Python 在Exception之后重新输入try语句
在下面的代码中,当我遇到异常时,它停止执行。如何让它从异常停止的位置重新输入Python 在Exception之后重新输入try语句,python,exception,exception-handling,try-except,Python,Exception,Exception Handling,Try Except,在下面的代码中,当我遇到异常时,它停止执行。如何让它从异常停止的位置重新输入try语句?也许我正在寻找一种不同的方法来解决这个问题,而不需要一个“尝试除外”的声明 import requests from requests import exceptions contains_analyst = [] try: for x in data: r = requests.get(str(x), timeout=10, verify=False) if "
try
语句?也许我正在寻找一种不同的方法来解决这个问题,而不需要一个“尝试除外”的声明
import requests
from requests import exceptions
contains_analyst = []
try:
for x in data:
r = requests.get(str(x), timeout=10, verify=False)
if "analyst" in r.text:
contains_analyst.append("Analyst")
print "Analyst @ %s" % x
else:
contains_analyst.append("NOPERS")
print "Nopers"
except exceptions.RequestException:
contains_analyst.append("COULD NOT CONNECT")
您应该将try/except仅放在要捕获其错误的零件周围。在您的示例中,看起来您想要的更像这样:
for x in data:
try:
r = requests.get(str(x), timeout=10, verify=False)
except exceptions.RequestException:
contains_analyst.append("COULD NOT CONNECT")
else:
if "analyst" in r.text:
contains_analyst.append("Analyst")
print "Analyst @ %s" % x
else:
contains_analyst.append("NOPERS")
print "Nopers"
这里我使用try
块的else
子句来处理没有引发异常的情况(请参阅)。在许多情况下,如果您不需要在异常之后执行任何其他操作,您可以在该点返回,并将以下无异常代码放入主函数体中,从而稍微减少缩进:
for x in data:
try:
r = requests.get(str(x), timeout=10, verify=False)
except exceptions.RequestException:
contains_analyst.append("COULD NOT CONNECT")
return contains_analyst
# execution reaches here if no exception
if "analyst" in r.text:
contains_analyst.append("Analyst")
print "Analyst @ %s" % x
else:
contains_analyst.append("NOPERS")
print "Nopers"
当然,在那一点返回是否有意义取决于代码周围的上下文。Ahh,这是有意义的。我不知道为什么我认为我必须保持整个try声明的原样…谢谢