2

How can I test if a function returned an exception object if I don't know in advance what type of exception has been raised?

def func():
    try:
        bad_thing_happens  # NameError("global name 'bad_thing_happens' is not defined",)
        return True
    except Exception as e:
        return e

result = func()
if result == Exception:
    print 'a bad thing happened'

In this case the if statement returns False and I would miss the exception?

3
  • 2
    Just let the exception propagate outside the function and then catch it somewhere else. You don't need to catch it and then return it, an exception is for an exceptional circumstance not as a regular return. Commented Jun 8, 2016 at 3:02
  • 1
    Also, at least 9 times out of 10, catching Exception is a bad idea. If you don't know the type of exception, you very rarely actually know how to handle it properly... Sometimes the best thing you can do is let your program die, look at the stack trace to figure out why it died and fix the bug/logic so that it doesn't die the next time. Commented Jun 8, 2016 at 3:06
  • Thank you all for your great answers, exceptions just became a whole lot clearer :) Commented Jun 8, 2016 at 3:08

3 Answers 3

6

Functions returning exceptions instead of raising them or letting them bubble is a Bad Thing.

That said, you can test if an object is an instance of a class using isinstance(object, klass).

Sign up to request clarification or add additional context in comments.

Comments

5

The proper way would be to catch the exception outside of the function. For example:

def func():
    bad_thing_happens
    # NameError("global name 'bad_thing_happens' is not defined",)
    return True

try:
    result = func()
except NameError:
    print("a bad thing happened")

This makes it more clear where the exception is coming from (the function) and avoids the mess of trying to return an exception – after all, exceptions are generally meant to be caught and not returned.

Comments

2

If you cannot change the func() for some reason (for example, it is a part of a third-party library code), you can check the type of the returned value via isinstance():

if isinstance(result, Exception):
    print 'a bad thing happened'

If you can change func(), then you should not be returning exceptions - they are meant to be raised (and re-raised), caught and handled (and not handled, as well).

1 Comment

oooh, I like that :)

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.