Why is it recommended to use an exception instead of the BaseException class in Python?

The Python 2 documentation says that "programmers are encouraged to throw new exceptions from the Exception class or one of its subclasses, and not from BaseException." Without any further explanation as to why.

I am curious why it is so recommended? Is it easy to maintain a hierarchy of exceptions , as the Python developers intended?

>>> dir(BaseException) == dir(Exception) True 
+6
source share
1 answer

Exceptions derived from BaseException are: GeneratorExit , KeyboardInterrupt , SystemExit .

According to the documentation:

  • GeneratorExit : called when the close () method of the generator is called. It directly inherits from BaseException instead of StandardError, as this is technically not an error.
  • KeyboardInterrupt : Raises when the user presses an interrupt key (usually Control-C or Delete). At run time, interrupt checks are performed regularly. Interrupts introduced when the built-in function () or raw_input () input is waiting for input also raise this exception. The exception inherits from BaseException so as not to be accidentally caught by code that catches the exception and thus prevents the interpreter from exiting.
  • SystemExit : The exception inherits a BaseException instead of a StandardError or Exception, so it is no accident that code that catches the exception is caught. This eliminates the correct distribution and makes the interpreter exit.

So the usual reasons are to prevent try ... except Exception accidentally preventing the interpreter from exiting (except GeneratorExit )

UPDATE after watching Ashwini Chaudhary's comment:

PEP 352 - The required superclass for exceptions explains the reason.

Now that the hierarchy of exceptions is becoming even more important, since it has a basic root, a change in the existing hierarchy is required. As it stands now, if you want to catch all exceptions that signal an error and does not mean that the translator should be allowed to exit, you should specify all but two exceptions, specifically in the except clause, or catch two exceptions separately and then raise again them and all other exceptions seep into the section without exceptions:

 except (KeyboardInterrupt, SystemExit): raise except: ... 

It is useless obviously. This PEP offers a KeyboardInterrupt and SystemExit move to inherit directly from BaseException.

+10
source

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


All Articles