66

我在 urllib2 的 urlopen 中使用 timeout 参数。

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

我如何告诉 Python 如果超时到期,应该引发自定义错误?


有任何想法吗?

4

2 回答 2

102

在极少数情况下您要使用except:. 这样做会捕获任何难以调试的异常,它会捕获包括SystemExitand在内的异常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)
于 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 回答