Sobes.tech
Junior — Middle

What is the difference between the Exception class and the base class BaseException in Python?

sobes.tech AI

Answer from AI

In Python, the BaseException class is the base class for all built-in exceptions, including system exceptions such as SystemExit, KeyboardInterrupt, and GeneratorExit. The Exception class inherits from BaseException and serves as the base class for most user-defined and standard exceptions that are typically handled in programs.

Main difference:

  • BaseException is intended for all exceptions, including system ones that are usually not caught (e.g., user-initiated program interruption).
  • Exception is a subclass used for common errors that can and should be handled.

Example:

try:
    # code that might raise an exception
    pass
except Exception:
    # handle common exceptions
    pass

# But if you want to catch absolutely all exceptions, including system ones:
try:
    pass
except BaseException:
    pass

It is generally recommended to catch Exception so as not to intercept system exceptions that may signal the need to terminate the program.