处理urllib2的超时? - Python
我在使用urllib2的urlopen时,设置了一个超时时间。
urllib2.urlopen('http://www.example.org', timeout=1)
我该怎么告诉Python,如果超时时间到了,就应该抛出一个自定义的错误呢?
有什么想法吗?
2 个回答
20
在 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)
105
很少有情况需要使用 except:
。这样做会捕捉到 任何 异常,这会让调试变得很困难。而且,它还会捕捉到像 SystemExit
和 KeyboardInterrupt
这样的异常,这可能会让你的程序使用起来很麻烦。
最简单的情况是,你可以捕捉 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)