2015-06-23 47 views

回答

3

您正在尋找BaseException

用戶定義的異常類型應劃分爲Exception。請參閱docs

+0

非常感謝您的幫助.. ... :-) –

2

Exception的基類:

>>> Exception.__bases__ 
(BaseException,) 

Exception hierarchy從文檔證實,它是所有異常的基類:

BaseException 
+-- SystemExit 
+-- KeyboardInterrupt 
+-- GeneratorExit 
+-- Exception 
     +-- StopIteration 
     +-- ArithmeticError 
     | +-- FloatingPointError 
... 

捕獲所有異常的語法是:

try: 
    raise anything 
except: 
    pass 

注意:使用它非常非常謹慎,例如,你可以使用它在__del__清理過程中的方法,當世界可能被半毀,並沒有其他的選擇。

的Python 2允許提高不是從BaseException派生的異常:

>>> raise 1 
Traceback (most recent call last): 
    File "<stdin>", line 1, in <module> 
TypeError: exceptions must be old-style classes or derived from BaseException, not int 
>>> class A: pass 
... 
>>> raise A 
Traceback (most recent call last): 
    File "<stdin>", line 1, in <module> 
__main__.A: <__main__.A instance at 0x7f66756faa28> 

它是固定在Python 3,強制執行的規則:

>>> raise 1 
Traceback (most recent call last): 
    File "<stdin>", line 1, in <module> 
TypeError: exceptions must derive from BaseException 
+0

謝謝老闆的幫助........... –

+0

對我來說,'除了:'從來沒有成爲SyntaxError,它似乎不值得這個縮寫! (vs'除了BaseException:')。我想這是爲了方便和向後compat腳本(雖然我打賭大多數時間他們的意思'除了例外:')。 –

相關問題