2015-06-23 42 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脚本(虽然我打赌大多数时间他们的意思'除了例外:')。 –

相关问题