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)