编写一个Python函数,该函数接受一个函数和一个列表作为参数,将列表中的每个元素传递给函数,并将结果作为新的列表返回。但要求在调用过程中捕获所有异常,并将异常信息作为结果的一部分返回。
def apply_function_with_exception_handling(func, input_list):
"""
将输入列表中的每个元素传递给函数,并捕获所有异常,将异常信息作为结果的一部分返回。
参数:
func: 可调用的函数
input_list: 输入列表
返回:
包含函数调用结果或异常信息的新列表
"""
result = []
for item in input_list:
try:
# 调用函数并捕获结果
output = func(item)
result.append(output)
except Exception as e:
# 捕获异常并将异常信息添加到结果中
result.append(f"Exception occurred: {str(e)}")
return result
# 示例函数
def divide_by_two(x):
return x / 2
def square_root(x):
if x < 0:
raise ValueError("Cannot take square root of a negative number")
return x ** 0.5
# 示例调用
input_list = [1, 2, 0, -1, "a"]
# 调用 divide_by_two 函数
results_divide = apply_function_with_exception_handling(divide_by_two, input_list)
print(results_divide) # 输出: [0.5, 1.0, 0.0, -0.5, "Exception occurred: unsupported operand type(s) for /: 'str' and 'int'"]
# 调用 square_root 函数
results_sqrt = apply_function_with_exception_handling(square_root, input_list)
print(results_sqrt) # 输出: [1.0, 1.4142135623730951, 0.0, "Exception occurred: Cannot take square root of a negative number", "Exception occurred: '>=' not supported between instances of 'str' and 'int'"]
函数说明
apply_function_with_exception_handling是一个通用的函数,它接受一个函数func和一个列表input_list作为参数。- 函数会遍历
input_list中的每个元素,并将其传递给func进行处理。 - 在处理过程中,如果
func抛出异常,异常信息会被捕获并添加到结果列表中。 - 如果没有异常,
func的返回值会被添加到结果列表中。
示例分析
-
divide_by_two函数用于将输入值除以 2。对于列表[1, 2, 0, -1, "a"],处理结果如下:- 对于
1和2,结果分别是0.5和1.0。 - 对于
0,结果是0.0。 - 对于
-1,结果是-0.5。 - 对于
"a",由于字符串不能与整数进行除法运算,抛出异常并捕获异常信息。
- 对于
-
square_root函数用于计算输入值的平方根。对于列表[1, 2, 0, -1, "a"],处理结果如下:- 对于
1和2,结果分别是1.0和1.414...。 - 对于
0,结果是0.0。 - 对于
-1,由于负数没有实数平方根,抛出异常并捕获异常信息。 - 对于
"a",由于字符串无法与整数比较,抛出异常并捕获异常信息。
- 对于
总结
通过这种方式,可以确保所有异常都被捕获并作为结果的一部分返回,避免了程序因为异常而中断,同时提供了清晰的错误信息。