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
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)