【问题标题】:Re-enter try statement after an except在 except 之后重新输入 try 语句
【发布时间】:2014-05-07 04:02:40
【问题描述】:

在我下面的代码中,当我遇到异常时它会停止执行。我怎样才能让它从异常停止的地方重新输入try 语句?也许我正在寻找一种不使用 try-except 语句来解决此问题的不同方法?

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") 

【问题讨论】:

    标签: python exception exception-handling try-except


    【解决方案1】:

    你应该把 try/except 放在 only 你想捕获错误的部分。在您的示例中,您似乎想要更多这样的东西:

    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 子句来处理没有引发异常的情况(参见documentation)。在很多情况下,如果你在异常之后不需要做任何其他事情,你可以在该点返回并将以下无异常代码放在 main 函数体中,减少一点缩进:

    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"
    

    当然,此时返回是否有意义取决于代码的周围上下文。

    【讨论】:

    • 啊,有道理。我不知道为什么我认为我必须保持整个 try 语句原样......谢谢
    猜你喜欢
    • 1970-01-01
    • 2011-09-29
    • 2020-06-08
    • 1970-01-01
    • 2013-04-10
    • 2017-11-30
    • 2021-01-16
    • 2011-09-20
    • 2018-02-24
    相关资源
    最近更新 更多