【问题标题】:Is it bad form to intentionally trigger an excect block [closed]故意触发一个excect块是不好的形式[关闭]
【发布时间】:2013-04-05 13:14:11
【问题描述】:

有没有更好的方法来做这样的事情:

class SpecialError(Exception):
    pass

try:
    # Some code that might fail
    a = float(a)
    # Some condition I want to check
    if a < 0:
        raise SpecialError
except (ValueError, SpecialError):
    # This code should be run if the code fails
    # or the condition is not met
    a = 999.

【问题讨论】:

  • 不,有很多用例可以引发异常。不过,在这种情况下,我只会提出 ValueError,不需要自定义。
  • 为什么不在进入区块前检查条件?

标签: python exception-handling try-catch


【解决方案1】:

显式引发异常显然在广泛的用例中很有用。但是,当您提出专门要在本地范围内捕获的异常时,您可能正在谈论与您的情况类似的一小部分案例。

一般来说也没有错。在任何给定的用例中,它可能是或可能不是最易读的代码,或者最能传达您的意图的代码,但这确实是一种风格判断。

您可以毫无例外地这样做,但会以轻微的 DRY 违规为代价:

try:
    # Some code that might fail
    b = float(a)
    # Some condition I want to check
    if b < 0:
        b = 999.
except ValueError:
    # This code should be run if the code fails
    # or the condition is not met
    b = 999.

…或者以稍微重新排序逻辑为代价:

b = 999.
if a >= 0:
    try:
        b = float(a)
    except ValueError:
        pass

或者,不要创建SpecialError,而是使用ValueError。由于它不会逃出这个块,而且你的代码无论如何都会对它们进行相同的处理,所以它不会添加任何东西:

try:
    b = float(a)
    if b < 0:
        raise ValueError
except ValueError:
    b = 999.

使用您最喜欢的其中一个,没有人会抱怨。如果您最喜欢的那个不涉及raise,那么我想答案是,“是的,有更好的方法”;如果是这样,答案是,“不,这是最好的方法。” :)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-30
    • 2015-11-09
    • 2021-11-03
    • 2010-11-27
    • 1970-01-01
    • 2015-12-30
    相关资源
    最近更新 更多