Search GimmeJob

Type at least 2 characters. Enter also searches by meaning.
Python interview question
Errors & context managersMiddleCommonTheory

Where does `Exception` sit in Python's exception hierarchy relative to `BaseException`, and why does that distinction matter for a bare `except:`?

Answer

`BaseException` is the root of the entire hierarchy, and `Exception` is one of its direct subclasses that covers essentially all error conditions application code is expected to handle. Critically, `SystemExit`, `KeyboardInterrupt` and `GeneratorExit` inherit directly from `BaseException`, not from `Exception`, specifically so that a normal `except Exception:` will not accidentally swallow a user's Ctrl+C or a deliberate `sys.exit()` call. A bare `except:` catches everything, including those three, which is why it is almost always the wrong choice compared to `except Exception:`.

Strong answer includes

  • BaseException is the root, Exception is a subclass for ordinary errors
  • SystemExit/KeyboardInterrupt/GeneratorExit inherit BaseException directly, not Exception
  • bare except: catches those too, unlike except Exception:

Practical example

A bare

Python example
except:

inside a retry loop can accidentally catch and suppress `KeyboardInterrupt` , making a program that appears to hang and completely ignore Ctrl+C.

#exceptions#error-handling

Sources

Errors and ExceptionsPython Software Foundation · try/except/else/finally control flow and exception chainingThe Python Language ReferencePython Software Foundation · Precise scoping, evaluation order and expression semantics