Phase 3 of 25 · Topic 3.3

Exception Hierarchy: BaseException vs Exception & Tracebacks

1Concept

In Python, `BaseException` is the root of all exceptions. System-exiting exceptions (`KeyboardInterrupt`, `SystemExit`) inherit from `BaseException`. Application and domain errors MUST inherit from `Exception`. Catching `BaseException` intercepts Ctrl+C and breaks process lifecycle handling.

2Architecture Diagram

BaseException
  ├── KeyboardInterrupt  (Ctrl+C - NEVER CATCH IN APP CODE!)
  ├── SystemExit         (sys.exit())
  └── Exception          (Root of all application exceptions)
        ├── ValueError, TypeError, RuntimeError, KeyError

3Code Example

Python 3.12
import traceback

def divide_operation(a, b):
    try:
        return a / b
    except ZeroDivisionError as e:
        print(f"[Handled Error] {type(e).__name__}: {e}")
        return 0.0

print(f"Result 1: {divide_operation(10, 2)}")
print(f"Result 2: {divide_operation(10, 0)}")

4Expected Output

Result 1: 5.0
[Handled Error] ZeroDivisionError: division by zero
Result 2: 0.0

5Key Takeaways

  • NEVER write `except BaseException:`; always catch specific exceptions or `except Exception:`.
  • Use `raise NewException("...") from original_err` for explicit exception chaining.
  • Inspect tracebacks using the `traceback` standard library module.