Ojasa Mirai

Ojasa Mirai

Python

Loading...

Learning Level

🟢 BeginneršŸ”µ Advanced
Exceptions OverviewException TypesTry-Except BlocksRaising ExceptionsCustom ExceptionsMultiple ExceptionsFinally & CleanupDebugging TechniquesLogging Best Practices
Python/Error Handling/Exception Hierarchy

šŸ—ļø Exception Types and Hierarchy — Understanding Python's Exception Family

Learn how Python organizes exceptions and recognize the most common types you'll encounter.


šŸ“š The Exception Hierarchy

Python organizes exceptions in a tree structure. At the top is `BaseException`, with `Exception` as the most common parent for errors we handle:

# Simplified exception hierarchy
BaseException
ā”œā”€ā”€ Exception
│   ā”œā”€ā”€ ArithmeticError
│   │   ā”œā”€ā”€ ZeroDivisionError
│   │   ā”œā”€ā”€ OverflowError
│   │   └── FloatingPointError
│   ā”œā”€ā”€ LookupError
│   │   ā”œā”€ā”€ IndexError
│   │   └── KeyError
│   ā”œā”€ā”€ OSError (FileNotFoundError, etc.)
│   ā”œā”€ā”€ TypeError
│   ā”œā”€ā”€ ValueError
│   ā”œā”€ā”€ AttributeError
│   ā”œā”€ā”€ NameError
│   └── ... (many more)
ā”œā”€ā”€ KeyboardInterrupt
└── SystemExit

šŸ” Common Exception Types Explained

# 1. ZeroDivisionError - cannot divide by zero
try:
    result = 10 / 0
except ZeroDivisionError as e:
    print(f"Math error: {e}")

# 2. ValueError - wrong value for data type
try:
    number = int("abc")  # "abc" cannot convert to int
except ValueError as e:
    print(f"Value error: {e}")

# 3. IndexError - list index out of bounds
try:
    items = ["a", "b", "c"]
    print(items[10])  # Only indices 0, 1, 2 exist
except IndexError as e:
    print(f"Index error: {e}")

# 4. KeyError - dictionary key doesn't exist
try:
    student = {"name": "Alice", "age": 20}
    print(student["email"])  # "email" key not in dict
except KeyError as e:
    print(f"Key error: {e}")

# 5. TypeError - wrong data type for operation
try:
    result = "5" + 10  # Can't add string and integer
except TypeError as e:
    print(f"Type error: {e}")

# 6. AttributeError - object doesn't have attribute
try:
    text = "hello"
    print(text.upper_case)  # No 'upper_case' method
except AttributeError as e:
    print(f"Attribute error: {e}")

# 7. NameError - variable doesn't exist
try:
    print(undefined_variable)
except NameError as e:
    print(f"Name error: {e}")

# 8. FileNotFoundError - file doesn't exist
try:
    with open("/nonexistent/file.txt") as f:
        content = f.read()
except FileNotFoundError as e:
    print(f"File error: {e}")

šŸŽÆ Catching Exceptions by Type

You can catch specific exception types to handle different errors differently:

# Different handling for different errors
def get_user_data(user_id, data_dict):
    try:
        # Could raise KeyError or TypeError
        user = data_dict[user_id]
        age = int(user["age"])
        return age
    except KeyError as e:
        print(f"Missing data: {e}")
        return None
    except TypeError as e:
        print(f"Type mismatch: {e}")
        return None
    except ValueError as e:
        print(f"Invalid value: {e}")
        return None

# Works fine
users = {1: {"name": "Alice", "age": "25"}}
print(get_user_data(1, users))  # Returns 25

# Handles missing key
print(get_user_data(2, users))  # KeyError handled

# Handles type error
print(get_user_data("wrong", users))  # TypeError handled

🧬 Related Exceptions (Parent Classes)

Some exceptions are related through parent classes. Catching the parent catches all children:

# LookupError is parent of IndexError and KeyError
try:
    items = [1, 2, 3]
    print(items[10])  # IndexError is a LookupError
except LookupError:  # Catches both IndexError AND KeyError
    print("Item not found!")

# ArithmeticError is parent of ZeroDivisionError
try:
    result = 10 / 0  # ZeroDivisionError is an ArithmeticError
except ArithmeticError:
    print("Math error occurred!")

# OSError is parent of FileNotFoundError, PermissionError, etc.
try:
    with open("/restricted/file.txt") as f:
        content = f.read()
except OSError as e:  # Catches file-related errors
    print(f"File system error: {e}")

šŸ“Š Common Exceptions Reference Table

ExceptionCauseExample
`ZeroDivisionError`Division by zero`10 / 0`
`ValueError`Wrong value for type`int("abc")`
`IndexError`List index out of range`[1,2][5]`
`KeyError`Dict key doesn't exist`{}["missing"]`
`TypeError`Wrong data type`"text" + 5`
`AttributeError`Attribute doesn't exist`"text".missing_method()`
`NameError`Variable doesn't exist`undefined_var`
`FileNotFoundError`File doesn't exist`open("missing.txt")`
`ImportError`Module can't import`import nonexistent`
`RuntimeError`General runtime errorVarious scenarios

šŸ”— Exception Relationships

# Checking exception relationships
exceptions = [
    ValueError,
    IndexError,
    KeyError,
    ZeroDivisionError,
    FileNotFoundError
]

print("Exception hierarchies:")
for exc in exceptions:
    # Get parent classes
    bases = exc.__bases__[0].__name__
    print(f"  {exc.__name__} -> {bases}")

# Output:
# ValueError -> Exception
# IndexError -> LookupError
# KeyError -> LookupError
# ZeroDivisionError -> ArithmeticError
# FileNotFoundError -> OSError

āš ļø Standard vs Built-in Exceptions

# Standard exceptions (built into Python)
# These are always available, no import needed

try:
    result = 10 / 0
except ZeroDivisionError:
    print("Built-in exception handled!")

# Some exceptions need imports but are still "built-in"
import json
try:
    json.loads("invalid")
except json.JSONDecodeError:
    print("JSON parsing error!")

# You can also create custom exceptions
# (covered in Custom Exceptions lesson)

šŸŽÆ Key Takeaways

  • āœ… Exceptions form a hierarchy with `Exception` as the main parent
  • āœ… `LookupError` parent catches both `IndexError` and `KeyError`
  • āœ… `ArithmeticError` parent catches math-related errors
  • āœ… `OSError` parent catches file system errors
  • āœ… Specific exception catching makes code more maintainable
  • āœ… Understanding relationships helps write better error handling


Resources

Python Docs

Ojasa Mirai

Master AI-powered development skills through structured learning, real projects, and verified credentials. Whether you're upskilling your team or launching your career, we deliver the skills companies actually need.

Learn Deep • Build Real • Verify Skills • Launch Forward

Courses

PythonFastapiReactJSCloud

Ā© 2026 Ojasa Mirai. All rights reserved.

TwitterGitHubLinkedIn