why should we use Exception as a superclass, why not BaseException

こ雲淡風輕ζ 提交于 2019-12-04 03:31:33

问题


In python, whenever we are writing User-defined exception, we have to extend it from class 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.


回答1:


BaseException includes things like KeyboardInterrupt and SystemExit, which use the exception mechanism, but which most people shouldn't be catching. It's analogous to Throwable in Java, if you're familiar with that. 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.




回答2:


Per the Python2 documentation, there are four exceptions that are derivatives of 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. BaseException was added in Python2.5 (before that, there was no BaseException and the other exceptions were subclassed from Exception).



来源:https://stackoverflow.com/questions/17802242/why-should-we-use-exception-as-a-superclass-why-not-baseexception

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!