I want to catch a urllib2.HTTPError with extra information if it’s a 404:
try:
data = urlopen(url)
except HTTPError, e: # Python 2.5 syntax
if e.code == 404:
raise HTTPError('data not found on remote')
else:
raise
but this doesn’t work because HTTPError‘s init takes multiple arguments, which are undocumented. It it did work, it would lose the backtrace and the original message. I also tried
if e.code == 404:
e.message = 'data not found on remote: %s' % e.message
raise
but that just re-raised the exception without extra information. What should I do?
You just need to use
e.msgrather thane.message. The script:prints
You can of course tidy this up with an enclosing try/except:
which prints simply
The exception has all of the original detail:
e.__dict__looks like