Python语句失败时的Python异常

时间:2016-10-22 19:03:28

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

我有一个简单的异常类:

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

1 个答案:

答案 0 :(得分:2)

只有几个嵌套的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