我们建一个urllib2_test09.py来示范一下第二种异常处理的方案:
from urllib2 import Request, urlopen, URLError, HTTPError
req = Request('//www.jb51.net/callmewhy')
try:
response = urlopen(req)
except URLError, e:
if hasattr(e, 'code'):
print 'The server couldn't fulfill the request.'
print 'Error code: ', e.code
elif hasattr(e, 'reason'):
print 'We failed to reach a server.'
print 'Reason: ', e.reason
else:
print 'No exception was raised.'
# everything is fine










