if语句失败时的Python异常

if语句失败时的Python异常,python,python-2.7,if-statement,exception-handling,nested-if,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

我有一个简单的异常类:

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
s对于这样简单的东西来说似乎很混乱(可能只是我)。。。我宁愿吃像这样的东西

if not self.active and len(self.recording) > index:
然后根据if失败的位置/方式引发异常

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

提前谢谢你


**我正在使用的一些库需要Python2.7,因此,如果s在我看来非常好,那么代码只适用于2.7

但是,您可能会使用如下
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

在这种情况下,由于
if
无条件地引发异常,因此它后面是
elif
还是
if
并不重要。这是真的,@tdelaney!!非常正确,非常正确!:-)我编辑了答案!谢谢,甚至没有考虑过反转< <代码> > < /COS> S到异常调用,这样就没有嵌套任何东西了。简单,聪明,没有嵌套。我喜欢!谢谢你们两位!如果您想要详细的错误消息,那么多个If是最好的选择。如果每一个
都产生一个独特的东西,那么它就不会过于健谈。使用防御方法!!!
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