【问题标题】:Python Exceptions for when an if statement failsif 语句失败时的 Python 异常
【发布时间】:2017-03-04 21:41:37
【问题描述】:

我有一个简单的异常类:

class Error(Exception):
    def __init__(self, msg):
        self.msg = msg
    def __str__(self):
        return self.msg

我还有一个 if 语句,我想根据失败情况抛出不同的异常。

if not self.active:
    if len(self.recording) > index:
        # something
    else:
        raise Error("failed because index not in bounds")
else:
    raise Error("failed because the object is not active")

这很好用,但嵌套ifs 让这种简单的东西看起来很乱(也许只是我)......我宁愿有类似的东西

if not self.active and len(self.recording) > index:

然后根据 if 失败的位置/方式抛出异常。

这样的事情可能吗?嵌套ifs(在第一个示例中)是解决此问题的“最佳”方式吗?

提前谢谢你!

**我使用的一些库需要 Python 2.7,因此,代码适用于 2.7

【问题讨论】:

  • 如果你想要详细的错误信息,那么多个 if 是要走的路。每个if 都会产生一个独特的东西,所以它不会过于健谈。
  • 使用防御方法!!!

标签: python python-2.7 if-statement exception-handling nested-if


【解决方案1】:

只有几个嵌套的ifs 在我看来非常好......

但是,您可以像这样使用elif

if not self.active:
    raise Error("failed because the object is not active")
elif len(self.recording) <= index:
   # The interpreter will enter this block if self.active evaluates to True 
   # AND index is bigger or equal than len(self.recording), which is when you
   # raise the bounds Error
   raise Error("failed because index not in bounds")
else:
   # something

如果 self.active 的计算结果为 False,您将收到错误消息,因为该对象未处于活动状态。如果它是活动的,但self.recording 的长度小于或等于索引,你会得到第二个索引不在范围内的错误,在任何其他情况下,一切都很好,所以你可以安全地运行@987654328 @

编辑:

正如@tdelaney 在他的评论中正确指出的那样,您甚至不需要elif,因为当您提出Exception 时,您将退出当前范围,所以应该这样做:

if not self.active:
    raise Error("failed because the object is not active")
if len(self.recording) <= index:
   raise Error("failed because index not in bounds")
# something

【讨论】:

  • 在这种情况下,由于if 无条件地引发异常,所以它后面是elif 还是if 都没有关系。
  • 非常真实,@tdelaney!非常对,非常对! :-) 我编辑了答案!谢谢
  • 甚至没有考虑将我的ifs 反转为异常调用,以便没有嵌套任何内容。简单,出色,没有嵌套。我喜欢!谢谢你们!
猜你喜欢
  • 2022-07-22
  • 2015-06-04
  • 2018-02-02
  • 2019-01-26
  • 2021-10-17
  • 2015-02-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多