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