【发布时间】: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