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

Is there a context that ignores multiple errors and continues execution without jumping?

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 循环在第一个异常发生时停止,执行跳转到 LINE-1。 Python 中是否有替代构造或设施,我们可以忽略上下文中发生的多个错误,并在上下文中从 LINE-A 到 LINE-Z 不间断地继续执行。即如果LINE-A发生异常,则继续执行LINE-B,而不是跳转到LINE-1。

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

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

用自己的 with suppress 包装 LINE-A 到 LINE-Z 的 each 是一种可能性,但可读性较差,所以我问是否有其他选择更多

这个呢?

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]