17

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.

7
  • 2
    um... have you actually tried isinstance(result, Exception)? works for me since e is an instance of StandardError not the class StandardError itself. Commented Dec 15, 2016 at 17:44
  • 3
    Why does your code do that? Commented Dec 15, 2016 at 17:44
  • 1
    This seems like an XY problem to me: perhaps you can step back and tell us what you are trying to accomplish? Commented Dec 15, 2016 at 17:46
  • 5
    I'd be curious to understand what you're trying to achieve by first storing one of two unrelated things in the same variable, to only later have difficulty figuring out which of the two things is stored there. Commented Dec 15, 2016 at 17:46
  • 1
    I recommend designing your code to be simpler, and thus avoiding this question altogether: set result=None and use a different name, eg err = e for the error. Then you can easily know if you have an error or a result: if err is None then no error and result is good otherwise you have an error. Commented Dec 15, 2016 at 17:46

2 Answers 2

34

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
Sign up to request clarification or add additional context in comments.

Comments

1

For anyone googling the subject and refusing to think they have run into XY problem:

You can access the type of any exception by instancing it and checking its type. Normally we use "str" and such to refer to a class, but to access the class for an exception we will have to instance it:

>>> type(ZeroDivisionError())
>>> <class 'ZeroDivisionError'>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.