繁体   English   中英

比较Python中的异常对象

[英]Comparing Exception Objects in Python

我是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)

(可能是一些语法错误)

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

对于大多数异常类,您可以使用测试功能相等性

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

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

您想要检查 异常的类型

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

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

在这种情况下,使用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
...

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM