174. Exception Hierarchy and Inheritance

Snippet 1: Viewing Python's Exception Hierarchy

import inspect

for cls in inspect.getmro(Exception):
    print(cls.__name__)

# Output:
# Exception
# BaseException
# object

Snippet 2: Basic Try-Except with Built-in Exceptions

try:
    x = 10 / 0
except ZeroDivisionError as e:
    print(f"Caught an exception: {e}")

Snippet 3: Catching Multiple Exceptions

try:
    x = int("abc")
except (ValueError, TypeError) as e:
    print(f"Caught an exception: {e}")

Snippet 4: Raising a Built-in Exception


Snippet 5: Creating a Custom Exception


Snippet 6: Custom Exception with Additional Attributes


Snippet 7: Using Inheritance for Custom Exceptions


Snippet 8: Catching and Reraising Exceptions


Snippet 9: Using __cause__ for Exception Chaining


Snippet 10: Ensuring Cleanup with finally


Last updated