174. Exception Hierarchy and Inheritance
Snippet 1: Viewing Python's Exception Hierarchy
Copy
import inspect
for cls in inspect.getmro(Exception):
print(cls.__name__)
# Output:
# Exception
# BaseException
# objectSnippet 2: Basic Try-Except with Built-in Exceptions
Copy
try:
x = 10 / 0
except ZeroDivisionError as e:
print(f"Caught an exception: {e}")Snippet 3: Catching Multiple Exceptions
Copy
Snippet 4: Raising a Built-in Exception
Copy
Snippet 5: Creating a Custom Exception
Copy
Snippet 6: Custom Exception with Additional Attributes
Copy
Snippet 7: Using Inheritance for Custom Exceptions
Copy
Snippet 8: Catching and Reraising Exceptions
Copy
Snippet 9: Using __cause__ for Exception Chaining
Copy
Snippet 10: Ensuring Cleanup with finally
Copy
Last updated