我有一個try子句中的命令,我知道拋出一個異常。我試圖在「except」子句中捕獲它,但except子句似乎無法識別異常的存在。唯一的例外,未處理的時候(即不包含在try子句中),看起來像這樣在交互窗口:python異常未被識別;如何處理除了?
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
的,當我把命令在try /除了在第一個文件構建在該列表中, 「actions.py」,像這樣:
try:
annotation=annotator.ncbo_annotate(thing)
except HTTPError:
...do some things with this
我預計,上述條款將在「HTTPError:HTTP錯誤500:內部服務器錯誤」趕上當我運行ncbo_annotate功能正在生產,而是當我運行以上,我收到一個錯誤,說全局名稱「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是什麼,或者,我如何告訴它它是什麼以便它能夠處理它?
你可以做的另一件事是之前HTTPError把它的命名空間,寫except子句這樣說:'除了urllib2.HTTPError:' – gerlos 2014-08-04 17:12:08