gpt4 book ai didi

Python if 语句失败时的异常

转载 作者:行者123 更新时间:2023-12-01 03:37:11 24 4
gpt4 key购买 nike

我有一个简单的异常类:

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")

这工作得很好,但是嵌套的 if 对于这个简单的东西看起来很困惑(也许只是我)......我更愿意有类似的东西

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

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

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

提前谢谢您!

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

最佳答案

只有几个嵌套的 if 对我来说看起来非常好......

但是,您可能可以像这样使用 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 的长度小于或等于索引,您将收到索引不在边界内的第二个错误,在任何其他情况下,一切都很好,所以您可以安全地运行# Something

编辑:

@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

关于Python if 语句失败时的异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40195939/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com