如何使用python lambdas捕获异常 [英] How to catch exceptions using python lambdas
问题描述
假定Python版本> = 3并调用函数列表.
我想编写一个处理异常的lambda函数.
事实是,它不起作用,当函数中引发异常时,程序返回并且调用堆栈未在其中看到executeFunction
.
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.
该怎么做?
def executeFunction(x):
try:
x
except:
print('Exception caught')
executeFunction(func1())
executeFunction(func2())
executeFunction(func3())
executeFunction(func4())
executeFunction(func5())
executeFunction(func6())
推荐答案
executeFunction
如果任何函数调用引发了异常,即在参数仍在求值的情况下,将不会调用.
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.
您应该考虑改为传递 callable 并在try/except
子句中调用它:
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)
x()
中出现的任何错误现在都由封闭的try/except
子句处理.
Any errors raised from x()
are now handled by the enclosing try/except
clause.
对于带有参数的函数,您可以使用 functools.partial
(或lambda
)以使用以下参数推迟呼叫:
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))
您还可以利用Python的装饰器语法直接使用对函数本身的调用,而不必直接明确调用executeFunction
,从而从调用方提供了更简洁的代码:
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)
这篇关于如何使用python lambdas捕获异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!