比较Python中的异常对象

2024-06-05 18:55:24 发布

您现在位置: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)

(可能是语法错误)

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


Tags: orifasexceptionerrorintegerurllib2division
3条回答

你想要to checkthe type of the exception

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

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

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

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

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

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

相关问题 更多 >