是否存在忽略多个错误并继续执行而不跳转的上下文?

2024-09-28 19:24:33 发布

您现在位置:Python中文网/ 问答频道 /正文

with suppress(ValueError):
    while test_condition:
        biglist.remove(222) # element that doesn't exist, raises error. but we dont care abt this error.
        # LINE-A: more remove kind of calls where we are dont care abt ValueError(s) raised
        # LINE-B: ...
        # ...
        # LINE-Z: ...

# LINE-1: some statement..
# some more statements...

使用contextlib.suppress,while循环在出现第一个异常时停止,执行跳到第1行。 Python中是否有一种替代的构造或功能,我们可以忽略上下文中发生的多个错误,并在上下文中从a行到Z行不间断地继续执行。也就是说,如果异常发生在第A行,执行将继续到第B行,而不是跳到第1行。你知道吗

使用multiple-try-except-finally覆盖从A行到Z行的每一行对我来说并不是一个干净的选择,因为它严重影响了可读性。你知道吗

try:
    #LINE-A...
except ValueError:
    pass
finally:
    try:
        #LINE-B...
     except ValueError:
        pass
     finally:
        #....

用它们自己的with suppress将A行到Z行的每个都包装起来是一种可能性,但是可读性较差,所以我想问是否有更多的替代方法


Tags: morewithlineerrorremovewedonttry
2条回答

如果你想彻底清除清单,你可以试试

while test_condition:
    biglist.clear()

如果您希望使用尝试删除每个值,请使用此

a = 220
while test_condition:
    try:
        biglist.remove(a)
    except ValueError:
        a -= 1
        continue

这个怎么样?你知道吗

def do_it(func, *args,suppress_exc=None, **kwargs):
    params = locals().copy()
    suppress_exc= suppress_exc or (ValueError,)
    try:
        func(*args, **kwargs)
        print("\nsweet  %s worked" % (params))
        return 0
    except suppress_exc as e: #pragma: no cover
        print("\nbummer %s failed" % (params))
        return e


biglist = [200, 300, 400]

while True:

    if not do_it(biglist.remove, 201):
        break

    if not do_it(biglist.pop, 6, suppress_exc=(IndexError,)):
        break

    if not do_it(biglist.remove, 200):
        break

    if not do_it(biglist.remove, 300):
        break

    if not do_it(biglist.remove, 400):
        break

print("done:biglist:%s" % (biglist))

输出:

bummer {'kwargs': {}, 'args': (201,), 'suppress_exc': None, 'func': <built-in method remove of list object at 0x106093ec8>} failed

bummer {'kwargs': {}, 'args': (6,), 'suppress_exc': (<class 'IndexError'>,), 'func': <built-in method pop of list object at 0x106093ec8>} failed

sweet  {'kwargs': {}, 'args': (200,), 'suppress_exc': None, 'func': <built-in method remove of list object at 0x106093ec8>} worked
done:biglist:[300, 400]

相关问题 更多 >