编写一个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'"]

函数说明

  1. apply_function_with_exception_handling 是一个通用的函数,它接受一个函数 func 和一个列表 input_list 作为参数。
  2. 函数会遍历 input_list 中的每个元素,并将其传递给 func 进行处理。
  3. 在处理过程中,如果 func 抛出异常,异常信息会被捕获并添加到结果列表中。
  4. 如果没有异常,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",由于字符串无法与整数比较,抛出异常并捕获异常信息。

总结

通过这种方式,可以确保所有异常都被捕获并作为结果的一部分返回,避免了程序因为异常而中断,同时提供了清晰的错误信息。