Skip to main content
 首页 » 编程设计

python之如何获取异常的实例类型

2025年05月04日9itcoder

我有这个代码:

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) 测试,但他们没有。

所以我想知道这个异常是什么实例。我该怎么做?

请您参考如下方法:

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

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