问题
I have a command in a try clause which I know throws an exception. I'm trying to catch it in an "except" clause, but the except clause seems to not recognize the existence of the exception. The exception, when unhandled (i.e. not enclosed in a try clause), looks like this in the interactive window:
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
The when I put the command in a try/except construct in the first file in that list, "actions.py", like this:
try:
annotation=annotator.ncbo_annotate(thing)
except HTTPError:
...do some things with this
I would expect that the above clause would catch the "HTTPError: HTTP Error 500: Internal Server Error" being produced when I run the ncbo_annotate function, but instead when I run the above, I am getting an error saying global name "HTTPError" is not defined:
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
So what's the deal? I thought python raises the exception until it finds a handler within a try clause or spits it out unhandled. Why does my code not have any idea what an HTTPError is, or alternatively, how do I tell it what it is so that it can handle it?
回答1:
You probably just need to import the HTTPError
class before using it. Try inserting at the top of your actions.py file:
from urllib2 import HTTPError
and then you should be able to use your code as is.
回答2:
In Python 3 it's:
from urllib.error import HTTPError
回答3:
You need to check for urllib2.HTTPError:
except urllib2.HTTPError:
回答4:
@Emily's solution is fine, but there's another way to solve this problem without importing that class.
You just need to give the full name space of the exception class you want to catch:
except urllib2.HTTPError:
This way you need fewer import
clauses in your code, and it's easier for you to tell afterwards which module raised the exception.
来源:https://stackoverflow.com/questions/15600707/nameerror-global-name-httperror-is-not-defined