python - 捕获异常得到 UnboundLocalError

标签 python exception

我编写了一个爬虫来从问答网站中获取信息。由于并非所有字段都始终显示在页面中,因此我使用了多个 try-excepts 来处理这种情况。

def answerContentExtractor( loginSession, questionLinkQueue , answerContentList) :
    while True:
        URL = questionLinkQueue.get()
        try:
            response   = loginSession.get(URL,timeout = MAX_WAIT_TIME)
            raw_data   = response.text

            #These fields must exist, or something went wrong...
            questionId = re.findall(REGEX,raw_data)[0]
            answerId   = re.findall(REGEX,raw_data)[0]
            title      = re.findall(REGEX,raw_data)[0]

        except requests.exceptions.Timeout ,IndexError:
            print >> sys.stderr, URL + " extraction error..."
            questionLinkQueue.task_done()
            continue

        try:
            questionInfo = re.findall(REGEX,raw_data)[0]
        except IndexError:
            questionInfo = ""

        try:
            answerContent = re.findall(REGEX,raw_data)[0]
        except IndexError:
            answerContent = ""

        result = {
                  'questionId'   : questionId,
                  'answerId'     : answerId,
                  'title'        : title,
                  'questionInfo' : questionInfo,
                  'answerContent': answerContent
                  }

        answerContentList.append(result)
        questionLinkQueue.task_done()

这段代码有时会或可能不会在运行时给出以下异常:

UnboundLocalError: local variable 'IndexError' referenced before assignment

行号表示错误发生在第二个except IndexError:

谢谢大家的建议,很想给你应得的分数,可惜我只能打一个正确答案......

最佳答案

我认为问题出在这一行:

except requests.exceptions.Timeout ,IndexError

这相当于:

except requests.exceptions.Timeout  as IndexError:

因此,您将 IndexError 分配给 requests.exceptions.Timeout 捕获的异常。此代码可以重现错误:

try:
    true
except NameError, IndexError:
    print IndexError
    #name 'true' is not defined

要捕获多个异常,请使用元组:

except (requests.exceptions.Timeout, IndexError):

UnboundLocalError 即将到来,因为 IndexError 被您的函数视为局部变量,因此在实际定义之前尝试访问其值将引发 UnboundLocalError 错误。

>>> 'IndexError' in answerContentExtractor.func_code.co_varnames
True

因此,如果此行未在运行时执行(requests.exceptions.Timeout ,IndexError),则下面使用的 IndexError 变量将引发 UnboundLocalError 。重现错误的示例代码:

def func():
    try:
        print
    except NameError, IndexError:
        pass
    try:
        [][1]
    except IndexError:
        pass
func()
#UnboundLocalError: local variable 'IndexError' referenced before assignment

关于python - 捕获异常得到 UnboundLocalError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21927065/

相关文章:

python - 将文本中的值替换为 python 字典中的整数值并求其总和

python - 使用 OpenCv 和 python 进行 RGB-D 姿态估计

javascript - IE 11 错误消息 - 由于错误 800a025e,无法完成操作

phpunit 测试 expectedException 不工作

python - 从 python 调用 Windows 的 icacls

Python:为什么将函数名称复制到本地 namespace 会导致更快的访问

python - Numpy IndexError 使用 genfromtxt 和第一列字符串读取 csv

C++11 noexcept 限定符和内联方法

c# - 如何连接两个异常?

android - 安卓工作室 SQLiteException : syntax error (code 1) while compiling