Python:证明规则的用户定义的异常

ban*_*ana 13 python exception

Python文档说明:

异常通常应直接或间接地从Exception类派生.

这个词'typically'让我处于模棱两可的状态.

考虑代码:

class good(Exception): pass
class bad(object): pass

Heaven = good()
Hell = bad()

>>> raise Heaven

Traceback (most recent call last):
  File "<pyshell#163>", line 1, in <module>
    raise Heaven
good

>>> raise Hell

Traceback (most recent call last):
  File "<pyshell#171>", line 1, in <module>
    raise Hell
TypeError: exceptions must be classes or instances, not bad
Run Code Online (Sandbox Code Playgroud)

所以阅读python文档的时候,我应该代替'typically'''

如果我有一个与Exception类无关的类层次结构,并且我想"提升"属于该层次结构的对象,该怎么办?

我总是可以用一个参数引发异常:

raise Exception, Hell
Run Code Online (Sandbox Code Playgroud)

这对我来说似乎有些尴尬

Exception(EDIT:或BaseException)类有什么特别之处,只有它的家庭成员可以被提升?

Mar*_*ers 21

Exception例如,除了可以继承的其他有效类之外BaseException.

请参阅异常层次结构的文档.

BaseException
 +-- SystemExit
 +-- KeyboardInterrupt
 +-- GeneratorExit
 +-- Exception
      +-- StopIteration
      +-- StandardError
      etc..
Run Code Online (Sandbox Code Playgroud)

在旧版本的Python中,除了异常之外还可以抛出其他东西.例如在Python 2.5中:

>>> raise "foo"
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
foo
Run Code Online (Sandbox Code Playgroud)

但是你得到这个弃用警告:

DeprecationWarning: raising a string exception is deprecated
Run Code Online (Sandbox Code Playgroud)

在较新的版本中,这是不允许的.你提出的一切都必须来自BaseException.


S.L*_*ott 9

"所以当阅读python文档时,我应该用''改变'通常'吗?"

没有.

通常,您从Exception继承.期.这就是它所说的.

有时,您可能会继承BaseException.这就是它没有说的.您可以扩展BaseExcetion,因为您想要打败except Exception处理程序.

什么是如此特别......

他们是子类BaseException.你还需要知道什么?来源随时可用.您可以阅读该raise语句的源代码,以便在它抛出之前确切地查看它所检查的内容TypeError.

http://svn.python.org/view/python/trunk/Python/ceval.c?annotate=80817

第3456至3563行.

然而,从实际角度来看,重要的是"子类" BaseException.