15

我是 Python 的新手,我被这个问题困住了。我正在尝试比较两个“异常对象”,例如:

try:
    0/0
except Exception as e:
    print e
>> integer division or modulo by zero

try:
    0/0
except Exception as e2:
    print e2
>> integer division or modulo by zero

e == e2
>> False

e is e2
>> False

我应该如何进行这种比较以获得“真”?

我正在尝试做的事情:

class foo():
    def bar(self, oldError = None):
        try:
            return urllib2.urlopen(someString).read()                   
        except urllib2.HTTPError as e:
            if e.code == 400: 
               if e != oldError: print 'Error one'
            else: 
               if e != oldError: print "Error two"
            raise
         except urllib2.URLError as e:
             if e != oldError: print 'Error three'
             raise

class someclass():        
    # at some point this is called as a thread
    def ThreadLoop(self, stopThreadEvent):
        oldError = None
        while not stopThreadEvent.isSet():
            try:
                a = foo().bar(oldError = oldError)
            except Exception as e:
                oldError = e
            stopThreadEvent.wait(3.0)

(可能是一些语法错误)

我为什么要这样做?因为我不想两次打印相同的错误

4

3 回答 3

26

对于大多数异常类,您可以使用

type(e) is type(e2) and e.args == e2.args

这测试它们的类是否完全相同,并且它们包含相同的异常参数。这可能不适用于不使用的异常类args,但据我所知,所有标准异常都可以。

于 2013-04-05T21:53:43.343 回答
7

您要检查 异常的类型

>>> isinstance(e2, type(e))
True

请注意,当然,这将允许子类 - 这是一件很奇怪的事情,所以我不确定你在寻找什么行为。

于 2013-04-05T21:48:26.373 回答
-1

在这种情况下,使用 str() 比较异常消息会很有用。

...
        except urllib2.HTTPError as e:
            if e.code == 400: 
                if isinstance(oldError, type(e)) and str(e) != str(oldError): 
                    print 'Error one'
            else: 
                if isinstance(oldError, type(e)) and str(e) != str(oldError): 
                    print "Error two"
            raise
         except urllib2.URLError as e:
             if isinstance(oldError, type(e)) and str(e) != str(oldError): 
                 print 'Error three'
             raise
...
于 2019-08-13T13:04:30.997 回答