简体   繁体   English

为什么我们应该使用Exception作为超类,为什么不使用BaseException

[英]why should we use Exception as a superclass, why not BaseException

In python, whenever we are writing User-defined exception, we have to extend it from class Exception . 在python中,每当我们编写用户定义的异常时,我们都必须从类Exception扩展它。 my question is why can't we extend it from BaseException which is super-class of exception hierarchy and Exception is also subclass of BaseException . 我的问题是为什么我们不能从BaseException扩展它,它是异常层次结构的超类,而Exception也是BaseException子类。

BaseException includes things like KeyboardInterrupt and SystemExit , which use the exception mechanism, but which most people shouldn't be catching. BaseException包括KeyboardInterruptSystemExit类的东西,它们使用异常机制,但是大多数人不应该抓住它。 It's analogous to Throwable in Java, if you're familiar with that. 如果您熟悉它,它类似于Java中的Throwable Things that derive directly from BaseException are generally intended to shut down the system while executing finally blocks and context manager __exit__ methods to release resources. 直接从BaseException派生的东西通常用于在执行finally块和上下文管理器__exit__方法时关闭系统以释放资源。

Per the Python2 documentation , there are four exceptions that are derivatives of BaseException : 根据Python2文档 ,有四个例外是BaseException衍生物:

BaseException
 +-- SystemExit
 +-- KeyboardInterrupt
 +-- GeneratorExit
 +-- Exception

The three that are not Exception are not actually errors, which means in general you don't want to catch them as if they are errors. Exception的三个实际上并不是错误,这意味着通常你不想捕获它们就好像它们是错误一样。 BaseException was added in Python2.5 (before that, there was no BaseException and the other exceptions were subclassed from Exception ). 在Python2.5中添加了BaseException (在此之前,没有BaseException ,其他异常是从Exception子类化的)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM