我在 urllib2 的 urlopen 中使用超时参数。
urllib2.urlopen('http://www.example.org', timeout=1)
我如何告诉Python,如果超时到期,应该引发自定义错误?
有任何想法吗?
您想要使用的情况很少except:
。这样做可以捕获any异常,这可能很难调试,它捕获的异常包括SystemExit
and 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)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)