and*_*ndy 14 python exception global-variables
我在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
Run Code Online (Sandbox Code Playgroud)
当我将命令放在该列表的第一个文件中的try/except结构时,"actions.py",如下所示:
try:
annotation=annotator.ncbo_annotate(thing)
except HTTPError:
...do some things with this
Run Code Online (Sandbox Code Playgroud)
我希望上面的子句能够捕获当我运行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
Run Code Online (Sandbox Code Playgroud)
那是什么交易?我认为python引发了异常,直到它在try子句中找到一个处理程序或者将它吐出未处理的状态.为什么我的代码不知道HTTPError是什么,或者我如何告诉它它是什么以便它可以处理它?
Emi*_*ily 25
您可能只需要HTTPError在使用之前导入该类.尝试插入actions.py文件的顶部:
from urllib2 import HTTPError
Run Code Online (Sandbox Code Playgroud)
然后你应该能够按原样使用你的代码.
ken*_*orb 19
在Python 3中它是:
from urllib.error import HTTPError
Run Code Online (Sandbox Code Playgroud)