针对多种例外情况的 DRY 方法

问题描述 投票:0回答:1

假设我们有以下代码:

try:
    whatever
except ValueError:
    something1
except (IndexError, KeyError):
    something2
except KeyBoardInterrupt:
    something3
except Exception:
    something4
else:  # no error
    something5
finally:
    finalize

所以我们有多个例外。我们是否有任何适合 DRY 方法的 else-antipod,因此只有在发生任何错误时才会执行?

例如,我们想要设置一些错误变量/标志或记录错误,但除此之外执行不同的 except 逻辑,而无需编写方法/函数

except_logic()
并在每个 except 中调用它。

python error-handling dry
1个回答
0
投票

如果您不关心处理订单,您可以执行以下操作:

error_state = True

try:
    print("Try")  # try raising here to see 'Error occurred'
except ...:
    ...
else:
    print("Else")
    error_state = False
finally:
    if error_state:
        print("Error occurred")

但是这样做更好(更具可读性)

def process_exception(e: Exception):
    # if isinstance(e, type1): ... and so on
    ...


try:
    print("Try")
except Exception as e:
    ...
    # do something common
    ...
    process_exception(e)
© www.soinside.com 2019 - 2024. All rights reserved.