66

urllib2のurlopen内でtimeoutパラメーターを使用しています。

urllib2.urlopen('http://www.example.org', timeout=1)

タイムアウトが期限切れになった場合、カスタムエラーを発生させる必要があることをPythonに伝えるにはどうすればよいですか?


何か案は?

4

2 に答える 2

102

を使用したい場合はほとんどありませんexcept:。これを行うと、デバッグが困難な可能性のある例外がキャプチャされ、およびを含む例外がキャプチャされるためSystemExitKeyboardInteruptプログラムの使用が煩雑になる可能性があります。

最も単純な場合、あなたはキャッチするでしょう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)
于 2010-04-26T10:30:46.400 に答える
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)
于 2013-01-31T18:13:04.943 に答える