I am new at Python and I'm stuck at this problem. I am trying to compare two "exception objects", example:
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
How should I perform this comparison to obtain a "True"?
What I am trying to do:
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)
(probably some syntax error)
Why I am doing that? Because I don't want to print the same error twice
Both “is” and “==” are used for object comparison in Python. The operator “==” compares values of two objects, while “is” checks if two objects are same (In other words two references to same object). The “==” operator does not tell us whether x1 and x2 are actually referring to the same object or not.
In Python, the difference between the is statement and the == operator is: The is statement checks if two objects refer to the same object. The == operator checks if two objects have the same value.
There are mainly three kinds of distinguishable errors in Python: syntax errors, exceptions and logical errors.
With most exception classes, you can test for functional equality with
type(e) is type(e2) and e.args == e2.args
This tests that their classes are exactly identical, and that they contain the same exception arguments. This may not work for exception classes that don't use args, but to my knowledge, all standard exceptions do.
You want to check the type of the exception:
>>> isinstance(e2, type(e))
True
Note, naturally, this will allow for subclasses - this is a weird thing to do, so I'm not sure what behaviour you are looking for.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With