← Back to Python Course | Chapter 10: Exception Handling | Lesson 5 of 5

Python Exception Hierarchy

The BaseException Class

BaseException sits at the very top of Python's exception tree -- every exception, including system-level ones like SystemExit and KeyboardInterrupt, ultimately inherits from it, which is exactly why catching 'except Exception:' deliberately does NOT catch those two (they skip past Exception in the hierarchy).

Example: The BaseException Class

python
print(issubclass(SystemExit, BaseException))
print(issubclass(SystemExit, Exception))

The Exception Class

Exception is the parent of nearly every normal error your code will raise or catch, and it's the class the documentation recommends your own custom exceptions inherit from -- catching except Exception: is broad but still excludes those system-exit signals.

Example: The Exception Class

python
try:
    int("abc")
except Exception as e:
    print("Caught by Exception:", type(e).__name__)

The ArithmeticError Family

ArithmeticError groups math-related failures under one umbrella -- ZeroDivisionError (dividing by zero) and OverflowError (a result too large to represent) both inherit from it, so catching ArithmeticError handles either without listing them separately.

Example: The ArithmeticError Family

python
try:
    1 / 0
except ArithmeticError:
    print("Caught a ZeroDivisionError via ArithmeticError")

The LookupError Family

LookupError groups the two most common couldnt find that' errors -- IndexError (list index out of range) and KeyError (dictionary key missing) -- letting you write one except clause that handles either kind of lookup failure.

Example: The LookupError Family

python
try:
    [1, 2][5]
except LookupError:
    print("Caught an IndexError via LookupError")

Order of Catching

Because except clauses are checked top to bottom and the first match wins, you must list more specific exception types before their more general parent classes -- an except Exception: block placed first would silently swallow every specific handler written after it.

Example: Order of Catching

python
try:
    1 / 0
except ZeroDivisionError:
    print("Specific handler runs first")
except Exception:
    print("This would swallow everything if placed first")
🔒

Chapter Quiz — Complete all 5 topics to unlock

0/5 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.