使用python如何优雅地精简try except循环?

使用python在主函数中进行重复引用各个子函数, 例如, def main(): try:A() except:Error() try:B() ex…
关注者
5
被浏览
6,099

1 个回答

from functools import wraps
def print_error(func):
    def usererror(ex, funcname):
        return type(ex)(str(ex) + '    (from function: {})'.format(funcname))
    @wraps(func)
    def wrapper(*args, **kwargs):
        try:
            result = func(*args, **kwargs)
        except Exception as ex:
            raise usererror(ex, func.__name__)
        return result
    return wrapper
@print_error