gpt4 book ai didi

python - 尝试多次尝试,但如果其中一次失败(最后)则引发错误

转载 作者:行者123 更新时间:2023-12-05 08:45:33 27 4
gpt4 key购买 nike

所以我说了 3 个我想运行的函数。他们每个人都可能失败。我想围绕它们构建 try-except 以:

  • 让尽可能多的 3 人跑 AND
  • 如果其中任何一个失败,最后会引发一个错误。这可能吗?

以下代码因操作 D(中间失败)而失败,因此永远不会到达 E:

try:
c = 3 + 6
print(c)
except TypeError:
raise TypeError("Wrong type provided in operation C")

try:
d = 3 + '6'
print(d)
except TypeError:
raise TypeError("Wrong type provided in operation D")

try:
e = 7 + 5
print(e)
except TypeError:
raise TypeError("Wrong type provided in operation E")

最佳答案

def f1():
print("f1")

def f2():
raise TypeError
print("f2")

def f3():
print("f3")


err = None

for f in [f1, f2, f3]:
try:
f()
except TypeError as e:
# store first error
if not err:
err = e

if err:
raise err

输出:

f1
f3
[...]
TypeError

如果你的函数有参数,你可以循环

[(f1, f1_args, f1_kwargs), (f2, f2_args, f2_kwargs), (f3, f3_args, f3_kwargs)]

受到评论的启发,我试图想出一个漂亮的上下文管理器,它在退出时以嵌套方式引发所有异常。欢迎评论。

class ErrorCollector:
def __init__(self):
self.errors = []

def exec(self, f, suppress_types=None, *args, **kwargs):
suppress_types = tuple(suppress_types) if suppress_types else ()

try:
return f(*args, **kwargs)
except suppress_types as e:
self.errors.append(e)

def _raise_all(self, errors):
if len(errors) == 1:
raise errors[0]

for e in errors:
try:
raise e
except type(e):
self._raise_all(errors[1:])

def __enter__(self):
return self

def __exit__(self, exctype, excinst, exctb):
if excinst is not None:
self.errors.append(excinst)
self._raise_all(self.errors)


def f1():
print('f1')

def f2():
raise TypeError('TypeError in f2')
print('f2')

def f3():
raise ValueError('ValueError in f3')
print('f3')

def f4():
raise TypeError('TypeError in f4')
print('f4')

def f5():
print('f5')

def f6():
raise ZeroDivisionError('ZeroDivisionError in f6')
print('f6')

def f7():
print('f7')

现在您可以使用:

suppress = [TypeError, ValueError]

with ErrorCollector() as ec:
for f in (f1, f2, f3, f4, f5, f6, f7):
ec.exec(f, suppress)

输出:

f1
f5
[...]
TypeError: TypeError in f2
During handling of the above exception, another exception occurred:
[...]
ValueError: ValueError in f3
During handling of the above exception, another exception occurred:
[...]
TypeError: TypeError in f4
During handling of the above exception, another exception occurred:
[...]
ZeroDivisionError: ZeroDivisionError in f6

请注意,f7 没有被执行,因为 ZeroDivisionError 没有被抑制。

关于python - 尝试多次尝试,但如果其中一次失败(最后)则引发错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72360291/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com