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

In python, whenever we write a custom exception, we must extend it from the Exception class. my question is why we cannot extend it from BaseException , which is a superclass of the exception hierarchy, and Exception also a subclass of BaseException .

+4
source share
2 answers

BaseException includes things like KeyboardInterrupt and SystemExit that use the exception mechanism, but which most people should not catch. This is similar to Throwable in Java if you are familiar with this. Things that are BaseException directly from BaseException are usually designed to shut down the system when finally blocks are executed and the __exit__ context manager is used to free resources.

+7
source

There are four exceptions in the Python2 documentation that are derived from BaseException :

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

Three that are not Exception are not really errors, which means you don’t want to catch them at all, as if they were errors. BaseException was added in Python2.5 (before that there was no BaseException , and the rest of the exceptions were subclassed from Exception ).

+3
source

Source: https://habr.com/ru/post/1492869/


All Articles