我正在使用urllib2的urlopen函数中的timeout参数。
urllib2.urlopen('http://www.example.org', timeout=1)
我应该如何告诉Python,如果超时就会引发自定义错误?
有什么想法吗?
很少有情况需要使用except:
。这样做会捕获所有异常,这可能很难调试,并且会捕获包括SystemExit
和KeyboardInterupt
在内的异常,这可能会让你的程序使用起来很烦人。
最简单的情况是,您可以捕获urllib2.URLError
:
try:
urllib2.urlopen("http://example.com", timeout = 1)
except urllib2.URLError, e:
raise MyException("There was an error: %r" % e)
当连接超时时,以下代码应该能够捕获特定的错误:
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)
socket.timeout
捕获。 - dbrurllib2.URLError
。从缓慢服务器读取响应的超时似乎会导致socket.timeout
。因此,总体来说,同时捕获这两种异常允许您区分这些情况。 - Kay在Python 2.7.3版本中:
import urllib2
import socket
class MyException(Exception):
pass
try:
urllib2.urlopen("http://example.com", timeout = 1)
except urllib2.URLError as e:
print type(e) #not catch
except socket.timeout as e:
print type(e) #catched
raise MyException("There was an error: %r" % e)
timeout
参数不限制连接的总时间或读取(响应)的总时间。 - jfs