在 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
廣告