2013-09-27 90 views
0

這是我得到:Exception類代碼不工作

class E2Exception(Exception): 
    pass 


class E2OddException(E2Exception): 
    pass 


def raiser(x): 
    if x == "So sue me!": 
     raise E2Exception 
    elif x != "So sue me!" and x not int: 
     raise ValueError 
    elif int(x) % 2 != 0: 
     raise E2OddException() 
    else: 
     return None 

我們怎麼說,如果x不轉換爲一個int,這樣做呢?

而且,我得到這個錯誤:

builtins.TypeError:異常必須從BaseException

得出這是什麼意思?

說明下面


E2Exception:一個異常類,是Exception一個子類。

E2OddException:一個異常類,是E2Exception一個子類。

raiser,即採用一個參數x,具有以下特性的函數:

  • 如果x == 'So sue me!',然後raiser(x)提高E2Exception與異常 消息"New Yorker"

  • 如果x != 'So sue me!',但x仍然不可轉換 爲int(通過調用int(x)),然後raiser(x)提出了ValueError,而不對異常消息

  • 如果x轉換到奇數int任何 要求,raiser(x)引發 E2OddException,而不會對異常消息的任何要求。

  • 否則,raiser(x)什麼也不做(沒有回報,沒有打印,什麼都沒有)。

+0

您應該'raise'例外,而不是'return'他們。 –

回答

1

How do we say if x is not convertible to an int, do this?

try: 
    int(x) 
except ValueError: 
    ... # Not convertable 
else: 
    ... # Convertable 

在這種情況下,你可能需要設置一個變量:

try: 
    int(x) 
except ValueError: 
    intable = True 
else: 
    intable = False 

您可以將您的代碼(而不是elif x != "So sue me!" and not intable:elif x != "So sue me!" and x not int:)的其餘內使用。


請注意,您

else: 
    return None 

是一個空操作,可完全去除。

+0

感謝您的幫助!問題是,我會在哪裏嵌入try - except - else代碼?再次感謝:) – muros

+0

另外,如果x不是intable,它是否會自動引發ValueError?會如果x == ValueError:做到這一點...工作? – muros

+0

在您需要使用intable變量之前,您會將它放入您的'raiser'函數中。如果它不能轉換它的值,那麼int'會產生一個'ValueError',是的。不過,我不確定你期望'x'永遠*等於*'ValueError'。 – Veedrac

1

int()引發傳遞時,輸入無效的異常,所以你可以讓這種情況發生,並擺脫你的return ValueError(這確實應該是一個raise)。

此外,Python的自動返回None如果你不明確返回任何東西,這樣可以簡化您的代碼只是:

def raiser(x): 
    if x == "So sue me!": 
     raise E2Exception("New Yorker") 
    elif int(x) % 2 != 0: 
     raise E2OddException() 
+0

如果x =='So sue me!',則raiser(x)會拋出異常消息「New Yorker」的E2Exception。那麼,是不是應該引發E2Exception?我如何將異常消息添加到E2Exception?非常感謝 – muros

+0

啊,沒關係,明白了!再次感謝 – muros

+0

@muros:您可以通過將參數作爲參數傳遞給任何異常來添加消息:'raise E2Exception(「New Yorker」)' – Blender