如何正確傳遞帶有 Python 中自定義異常的物件?
在給定的程式碼中,建立了自定義異常 FooException,它是超類 Exception 的一個子類。我們將一個字串物件傳遞給自定義異常,如下所示
舉例
#foobar.py class FooException(Exception): def __init__(self, text, *args): super ( FooException, self ).__init__ ( text, *args ) self.text = text try: bar = input("Enter a string:") if not isinstance(bar, basestring): raise FooException(bar) except FooException as r: print 'there is an error' else: print type(bar) print bar
如果在終端執行此指令碼,則得到
$ python foobar.py
如果我們輸入一個字串,會得到以下內容
輸出
"C:/Users/TutorialsPoint1/~foobar.py" Enter a string:'voila' <type 'str'> Voila
廣告