擅长:python、mysql、java
<p>很少有情况下需要使用<code>except:</code>。这样做可以捕获任何<em>异常,这可能很难调试,并且它捕获异常,包括<code>SystemExit</code>和<code>KeyboardInterupt</code>,这可能使您的程序使用起来很烦人。。</p>
<p>最简单地说,您可以捕获<a href="http://docs.python.org/library/urllib2.html#urllib2.URLError" rel="noreferrer">^{<cd4>}</a>:</p>
<pre><code>try:
urllib2.urlopen("http://example.com", timeout = 1)
except urllib2.URLError, e:
raise MyException("There was an error: %r" % e)
</code></pre>
<p>以下内容应捕获连接超时时引发的特定错误:</p>
<pre><code>import urllib2
import socket
class MyException(Exception):
pass
try:
urllib2.urlopen("http://example.com", timeout = 1)
except urllib2.URLError, e:
# For Python 2.6
if isinstance(e.reason, socket.timeout):
raise MyException("There was an error: %r" % e)
else:
# reraise the original error
raise
except socket.timeout, e:
# For Python 2.7
raise MyException("There was an error: %r" % e)
</code></pre>