1

I am trying to create generic exception handler - for where I can set an arg to return in case of exception.

instead of doing:

try:
    ...
except Exception:
    return list()

try:
    ...
except Exception:
    return dict()

try:
    ...
except Exception:
    return str()

I would like to create system whereby I have a generic exception handler that returns an arg I provide. e.g,

def handler(code, default):
    try:
        code
    except Exception:
        return default

def mains():
    code = <code to execute>
    default = str()
    return handler(code, dafault)

but in a more pythonic way

5
  • so you want to have something like "GENERIC_ERROR: problem solved". trial and error type-of problem solving? :-) Commented Nov 3, 2012 at 23:05
  • I'm confused as to what exactly you want to create. Could you show how this handler of yours would be used in client code? Commented Nov 3, 2012 at 23:07
  • this code will be in functions that should return a list, or another that returns a dict, or another that returns a number. I want to return a default value of an empty list, empty dict, or 0 in case of exceptions in these functions. Commented Nov 3, 2012 at 23:08
  • The "pythonic" way would be not doing this and just using a try..except directly to make the error handling obvious. Commented Nov 3, 2012 at 23:14
  • @millimoose Not necessarily. DRY is a fairly Pythonic concept. Commented Nov 3, 2012 at 23:20

1 Answer 1

4

A simple decorator will do this for you.

import functools


def catch_wrap(on_err):
    def wrapper(func):
        @functools.wraps(func)
        def inner(*args, **kw):
            try:
                return func(*args, **kw)
            except Exception:
                return on_err
        return inner
    return wrapper

A short example:

@catch_wrap('SPAM!')
def doer():
    """
    YUP
    """
    1 / 0
    return 'EGGS!'


print doer()
print doer.__doc__
Sign up to request clarification or add additional context in comments.

12 Comments

It's probably a good idea to use @functools.wraps for code like this.
@millimoose I don't think that wraps would do much extra in this case.
@pydisigner Oh, I missed that you're already taking steps to preserve __doc__. I guess because I'm so used to doing that with @wraps. (It does however do more than just __doc__)
@millimoose I just added that :). I don't think that the complexity of @functools.wrap is warranted.
There is a major hole in this; passing bad args will be masked. Time to dig out inspec.getargspec...
|

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.