Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comparing Exception Objects in Python

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

like image 857
Pedro Avatar asked Apr 05 '13 21:04

Pedro


People also ask

How do you compare two objects in Python?

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.

How do you check if two objects are identical in Python?

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.

What are the 3 major exception types in Python?

There are mainly three kinds of distinguishable errors in Python: syntax errors, exceptions and logical errors.


2 Answers

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.

like image 117
nneonneo Avatar answered Sep 21 '22 23:09

nneonneo


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.

like image 39
Gareth Latty Avatar answered Sep 22 '22 23:09

Gareth Latty