python - 动态使用try异常的问题

标签 python try-except

我有一个名为 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

我的代码:

from mimetypes import init


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

最佳答案

您应该在调用列表中的函数名称时执行此操作

func()

还修改了代码:

class ExceptionProxy(Exception):
    def __init__(self,msg,function):
        self.msg = msg
        self.function = function


def transform_exceptions(func_ls):
    out = []
    for x in func_ls:
        try:
            x()
            a = ExceptionProxy("ok!", x)
        except Exception as e:
            a = ExceptionProxy(str(e), x)
        out.append(a)
    return out

关于python - 动态使用try异常的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72939734/

相关文章:

python - 使用 mysqyl-python 连接器时出现 SSL 连接错误

Python读取Fortran二进制文件

python - mysql.connector多个查询: Error -1: No result set to fetch from

python - 只是用 lambda 尝试/排除 - Python?

python - 我如何使用堆栈跟踪来告诉我应该为Python的try/except使用哪个异常

python - try 和 except 都引发异常。

python - 用条件替换数据框值

python - 如何将列表拆分为大小相等的 block ?

python-2.7 - 异常属性错误 : "' NoneType' object has no attribute 'path' "in

python - 在Python中捕获特定的错误消息