Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

checking if an object is an Exception class

Tags:

python

I've got some code which does:

try:
    result = func()
except StandardError as e:
    result = e

How can I check whether result contains an Exception?

Using isinstance(result, Exception) doesn't work as exceptions are a class, not an instance, e.g. type(ValueError) gives <type 'type'>.

--- Edit ---

Well that was stupid; while the above code was a correct distillation of how I was using func(), what my test func() was doing was return ValueError, not raise ValueError. With the former returning the class and the latter returning an instance. So the problem wasn't as described.

like image 744
lost Avatar asked Dec 15 '16 17:12

lost


People also ask

How to check if an object is a certain class Python?

Using isinstance() function, we can test whether an object/variable is an instance of the specified type or class such as int or list. In the case of inheritance, we can checks if the specified class is the parent class of an object. For example, isinstance(x, int) to check if x is an instance of a class int .

How can I tell if an instance of an exception is available?

The java instanceof operator is used to test whether the object is an instance of the specified type (class or subclass or interface). catch (Exception e) { if(e instanceof NotAnInt){ // Your Logic. } else if if(e instanceof ParseError){ //Your Logic. } }

How to check if a variable is a class variable Python?

Python has a built-in function called type() that helps you find the class type of the variable given as input. Python has a built-in function called isinstance() that compares the value with the type given. If the value and type given matches it will return true otherwise false.

Is instance of object Python?

Python isinstance() Function The isinstance() function returns True if the specified object is of the specified type, otherwise False . If the type parameter is a tuple, this function will return True if the object is one of the types in the tuple.


1 Answers

Though I am convinced that this is an XY Problem that requires rethinking the logic of your design, here is an answer to your immediate question: isinstance works fine:

>>> try:
...     int('a')
... except ValueError as e:
...     result = e
...
>>> type(result)
<class 'ValueError'>
>>> isinstance(result, Exception)
True

Your problem is that you were testing ValueError (the class), not e (an instance of a ValueError). Perhaps the following example with a bool (which subclasses an int) will make this clearer:

>>> isinstance(bool, int)
False
>>> isinstance(True, int)
True
like image 96
brianpck Avatar answered Oct 20 '22 20:10

brianpck