Python 如何获取异常的实例类型?
我有以下代码:Python 如何获取异常的实例类型?,python,exception,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
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>
URLError in POST>reason=读取操作超时>
除了urlib2.URLError之外,这些都由处理。如果isinstance(error.reason,socket.timeout)
测试失败,它们应该通过
所以我想知道这个异常是什么。如何执行此操作?返回对象的类型
您可以使用打印类型(error.reason)
来诊断在这种情况下对象的类型reason
。使用以下方法:
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
type()?我必须修改我的代码,异常需要几个小时才能出现。。。或者它是类型(error.reason)
?打印类型(error.reason)
将帮助您诊断它是什么类型;答案不多,因此只是一个评论。为什么不!?这就是答案(如果可行的话)。所以我将测试它并接受它作为答案…呃,不是字符串表示,而是类型对象。抱歉,需要在那里多睡一会儿。我发现它是实例ssl.SSLError
。我想知道这与urllib2.urleror
Mmm有什么关系。我看到了ssl.SSLError
属于子类型socket.error
,属于子类型IOError
。我不知道它为什么要执行除了urlib2.urleror,error
代码。@gonvaled:urlib2
代码捕获该异常,然后引发urleror(originalexception)
,该参数存储为。reason
。