You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python动态使用try-except捕获函数异常封装ExceptionProxy问题

问题说明

需要实现transform_exceptions()函数,规则如下:

  • 接收元素为无参数函数的列表作为输入
  • 逐个调用列表内的函数,将执行过程中产生的异常转换为ExceptionProxy类的实例
  • 按原函数的传入顺序,返回封装后的对象列表
  • 若函数执行未抛出异常,同样创建ExceptionProxy对象,将其msg属性设置为"ok!"

题目给出的初始实现框架如下:

class ExceptionProxy(Exception):
    # define your class here

def transform_exceptions(func_ls):
    # implement your function here

def f():
    1/0

def g():
    pass

tr_ls = transform_exceptions([f, g])

for tr in tr_ls:
    print("msg: " + tr.msg + "\nfunction name: " + tr.function.__name__)

预期输出

msg: division by zero
function name: f
msg: ok!
function name: g
现有代码问题排查

你编写的代码存在两处问题:

  1. 存在无用的错误导入:from mimetypes import init,该行导入和当前实现逻辑完全无关,属于误加代码
  2. 核心逻辑错误:try块中仅写了func,只是对函数对象的引用,没有实际调用函数,因此所有函数的内部逻辑都不会执行,永远不会触发异常,所有返回对象的msg都会是"ok!",无法拿到异常信息。
修正后代码
class ExceptionProxy(Exception):
    def __init__(self, msg, function):
        self.msg = msg
        self.function = function


def transform_exceptions(func_ls):
    exception_list = []
    for func in func_ls:
        try:
            # 加括号实际调用函数,才会执行函数内部逻辑、触发可能的异常
            func()
        except Exception as e:
            r = ExceptionProxy(str(e), func)
            exception_list.append(r)
        else:
            r = ExceptionProxy("ok!", func)
            exception_list.append(r)
    return exception_list


# 测试逻辑
def f():
    1/0

def g():
    pass

tr_ls = transform_exceptions([f, g])

for tr in tr_ls:
    print("msg: " + tr.msg + "\nfunction name: " + tr.function.__name__)

运行上述代码即可得到和预期完全一致的输出。

内容的提问来源于stack exchange,提问作者Lalehe

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.27 05:03:20