generic exception handling return value

心不动则不痛 提交于 2019-12-24 15:01:27

问题


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


回答1:


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__


来源:https://stackoverflow.com/questions/13214377/generic-exception-handling-return-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!