How to catch exceptions using python lambdas

前端 未结 2 1495
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-01-14 10:55

Assuming Python version >=3 and calling a list of functions. I would like to write a lambda function that handles exceptions. Thing is, it does not work, when there is an ex

2条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-01-14 11:00

    executeFunction won't be called if the exception is raised by any of the function calls, that is, while the argument is still being evaluated.

    You should consider passing the callable instead and calling it inside the try/except clause:

    def executeFunction(x):
        try:
            x()
        except SomeException:
            print('Exception caught')
    
    executeFunction(func1)
    

    Any errors raised from x() are now handled by the enclosing try/except clause.

    For functions with arguments you can use functools.partial (or a lambda) to defer the call using the arguments:

    from functools import partial
    
    def executeFunction(x):
        try:
            x()
        except SomeException:
            print('Exception caught')
    
    executeFunction(partial(func1, arg1, argn))
    # executeFunction(lambda: func1(arg1, argn))
    

    You could also exploit Python's decorator syntax to use calls to the functions themselves directly without having to explicitly call executeFunction directly, giving much cleaner code from the caller's side:

    def executeFunction(func):
        def wrapper(*args, **kwargs):
            try:
                func(*args, **kwargs)
            except SomeException:
                print('Exception caught')
        return wrapper
    
    @executeFunction
    def func1(arg1, arg2):
        ...
    @executeFunction
    def func2(arg1):
        ...
    
    
    func1(arg1, arg2) # -> executeFunction(func1)(arg1, arg2)
    func2(arg1)       # -> executeFunction(func2)(arg1)
    

提交回复
热议问题