[英]Handling urllib2's timeout? - Python
我在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)
在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)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.