【问题标题】:How to get the instance type of an Exception?如何获取异常的实例类型?
【发布时间】:2012-12-30 13:10:41
【问题描述】:

我有这个代码:

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

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

【问题讨论】:

  • type() 为您提供对象类型或类的字符串表示形式。
  • 所以你的意思是我应该在这里做type(error)?我要修改我的代码,异常需要几个小时才会出现……还是type(error.reason)?
  • print type(error.reason) 将帮助您诊断它是什么类型;没有太多答案,因此只是评论。
  • 为什么不呢!?这是的答案(如果它有效)。所以我会测试它并接受它作为答案......
  • Erm,不是字符串表示,是类型对象。抱歉,需要多睡一会儿。

标签: python exception


【解决方案1】:

使用这个:

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

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

    • 我发现它的实例是ssl.SSLError。我想知道这与urllib2.URLError 有什么关系
    • 嗯。我看到了这个docs.python.org/2/library/ssl.html。 ssl.SSLError 是 socket.error 的子类型 IOError 的子类型。我不知道为什么它会通过except urllib2.URLError, error 代码。
    • @gonvaled:urllib2 代码捕获该异常,然后引发URLError(originalexception),该参数存储为.reason。
    猜你喜欢
    • 1970-01-01
    • 2014-12-21
    • 2019-09-22
    • 2016-02-05
    • 1970-01-01
    • 2019-03-08
    • 2021-03-20
    • 2010-11-27
    • 1970-01-01
    相关资源
    最近更新 更多