我在 try 子句中有一个命令,我知道它会引发异常。我试图在“except”子句中捕获它,但 except 子句似乎无法识别异常的存在。未处理的异常(即未包含在 try 子句中)在交互式窗口中如下所示:
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "C:\Users\Andy\software\Turkeys\actions.py", line 234, in annotate
annotation=annotator.ncbo_annotate(thing)
File "C:\Users\Andy\software\Turkeys\annotator.py", line 49, in ncbo_annotate
fh = urllib2.urlopen(submitUrl, postData)
File "C:\32Python27\lib\urllib2.py", line 126, in urlopen
return _opener.open(url, data, timeout)
File "C:\32Python27\lib\urllib2.py", line 406, in open
response = meth(req, response)
File "C:\32Python27\lib\urllib2.py", line 519, in http_response
'http', request, response, code, msg, hdrs)
File "C:\32Python27\lib\urllib2.py", line 444, in error
return self._call_chain(*args)
File "C:\32Python27\lib\urllib2.py", line 378, in _call_chain
result = func(*args)
File "C:\32Python27\lib\urllib2.py", line 527, in http_error_default
raise HTTPError(req.get_full_url(), code, msg, hdrs, fp)
HTTPError: HTTP Error 500: Internal Server Error
当我将命令放在该列表中第一个文件“actions.py”中的 try/except 构造中时,如下所示:
try:
annotation=annotator.ncbo_annotate(thing)
except HTTPError:
...do some things with this
我希望上面的子句会在我运行 ncbo_annotate 函数时捕获“HTTPError: HTTP Error 500: Internal Server Error”,但是当我运行上面的函数时,我收到一个错误,说全局名称“HTTPError”是没有定义的:
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "C:\Users\Andy\software\Turkeys\actions.py", line 235, in annotate
except HTTPError:
NameError: global name 'HTTPError' is not defined
那么有什么关系呢?我认为 python 会引发异常,直到它在 try 子句中找到处理程序或将其吐出未处理。为什么我的代码不知道 HTTPError 是什么,或者我如何告诉它它是什么以便它可以处理它?