通用的方法来避免广泛的p除外?

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

PEP8不喜欢广泛的异常处理

try:
    do_something()
except Exception:
    handle_exception()

我知道,有充分的理由像SystemExitKeyboardInterrupt以无意识的方式处理或丢失重要的错误案例。

但有时我认为我必须处理“所有其他”异常,例如:

while True:
    try:
        result = handle_request(get_request())
    except (all, my, known, exceptions) as ex:
        sophisticated_exception_handling()
    except (KeyboardInterrupt, SystemExit):
        raise
    except Exception as ex:
        # handle exotic situations which just didn't happen before
        result = "something bad happened: %r" % ex

在这个例子中,我不希望我的消息循环被中断只是因为一些子例程引发了一个我刚才没想过的异常。

当然我可以只是# pylint: disable这条线没有得到任何警告 - 但这并不是最复杂的答案。

所以我的问题是:

是否有一些很好的方法来很好地处理所有异常,因此永远不会忽略PEP8警告而从我的消息处理循环中掉出来?

python exception exception-handling pep8
1个回答
0
投票

看起来你有一个“特殊情况,基于实用性,应该击败纯度”,在PEP20中提到:

Special cases aren't special enough to break the rules.
Although practicality beats purity.

......而且......

Errors should never pass silently.
Unless explicitly silenced.

我相信你的代码不违反PEP20(又名The Zen of Python

© www.soinside.com 2019 - 2024. All rights reserved.