如何获取异常的实例类型?

时间:2013-01-16 09:06:52

标签: python exception

我有这段代码:

try:
    self.client.post(url, data, self.cookies, headers, auth, jsonrpc)
    self.status  = self.client.status
    self.mytime  = self.client.time
    self.text    = self.client.text
    self.length  = len(self.text)
except urllib2.URLError, error:
    print error
    self.exception = True
    self.urrlib2   = True
    if isinstance(error.reason, socket.timeout):
        self.timeout = True

但有时我会像这样打印出异常:

URLError in POST > reason=The read operation timed out > <urlopen error The read operation timed out>

这些由except urllib2.URLError处理。他们应该通过if isinstance(error.reason, socket.timeout)测试,但他们没有。

所以我想知道{1}这个例外是什么。我怎么能这样做?

2 个答案:

答案 0 :(得分:1)

type() function返回对象的类型。

在这种情况下,您可以使用print type(error.reason)来诊断对象reason的类型。

答案 1 :(得分:0)

使用此:

import sys

try:
    self.client.post(url, data, self.cookies, headers, auth, jsonrpc)
    self.status  = self.client.status
    self.mytime  = self.client.time
    self.text    = self.client.text
    self.length  = len(self.text)
except urllib2.URLError, error:
    print error
    self.exception = True
    self.urrlib2   = True

    errno, errstr = sys.exc_info()[:2]
    if errno == socket.timeout:
        print "There was a timeout"
        self.timeout = True
相关问题