擅长:python、mysql、java
<p>根据错误类型的不同,对象<code>e</code>可能携带也可能不携带该属性。</p>
<p>在您提供的链接中有一个更完整的示例:</p>
<blockquote>
<p><strong>Number 2</strong></p>
</blockquote>
<pre><code>from urllib2 import Request, urlopen, URLError
req = Request(someurl)
try:
response = urlopen(req)
except URLError, e:
if hasattr(e, 'reason'): # <--
print 'We failed to reach a server.'
print 'Reason: ', e.reason
elif hasattr(e, 'code'): # <--
print 'The server couldn\'t fulfill the request.'
print 'Error code: ', e.code
else:
# everything is fine
</code></pre>