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 exception thrown in a function, the program returns and the call stack is not seeing the executeFunction
in it.
How to do so?
def executeFunction(x):
try:
x
except:
print('Exception caught')
executeFunction(func1())
executeFunction(func2())
executeFunction(func3())
executeFunction(func4())
executeFunction(func5())
executeFunction(func6())
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:Any errors raised from
x()
are now handled by the enclosingtry/except
clause.For functions with arguments you can use
functools.partial
(or alambda
) to defer the call using the arguments: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:The short answer is that you can not really handle exceptions inside within an expression.
A longer answer would be: you may achieve what you want by using some contrived tricks. Of course you should not do that for serious purposes, but what you can actually do inside an expression is:
define "on the fly" new expressions by using tricky combinations of
type()
and ofsetattr()
, like this:raise any exception; not only by performing ad hoc operations but also in a more general manner if required:
catch some exceptions by tricky uses of ad hoc features like the way
StopIteration
is handled by iterators:You can read more about it at http://baruchel.github.io/python/2018/06/20/python-exceptions-in-lambda/ .