1

我有一個簡單的異常類:的Python例外,當一個if語句失敗

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

我也有一個,如果我想從取決於什麼失敗拋出不同的異常聲明。

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: 

再拋基於哪裏/如何如果失敗的例外。

是這樣的可能嗎?嵌套0​​s(在第一個示例中)解決此問題的「最佳」方式?

預先感謝您!

**我使用需要Python 2.7版的一些庫,因此,該代碼是2.7

+0

如果你想要詳細的呃ror消息,然後多個如果是要走的路。每個「if」產生一個獨特的東西,所以它不會過於健談。 – tdelaney

+0

使用防禦手段! – Shasha99

回答

2

只有一對夫婦嵌套if S的樣子完全沒有給我...

但是,你很可能使用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 
+2

在這種情況下,由於'if'無條件地引發了一個異常,所以它跟隨一個'elif'或'if'並不重要。 – tdelaney

+1

非常真實,@tdelaney!非常正確,非常正確! **: - )**我編輯了答案!謝謝 – BorrajaX

+1

甚至沒有考慮將我的'if's轉換爲異常調用,以免嵌套任何東西。簡單,輝煌,沒有嵌套。我喜歡!謝謝你們倆! – BrandonM