What You Will Learn
Intermediate
- How to create custom exceptions
- When to use them
- Building exception hierarchies
Terminalpython
class InvalidAgeError(Exception):
"""Raised when age is invalid."""
pass
class UnderageError(InvalidAgeError):
"""Raised when age is below minimum."""
def __init__(self, age, minimum=18):
self.age = age
self.minimum = minimum
super().__init__(f"Age {age} is below minimum {minimum}.")
def check_age(age):
if age < 0:
raise InvalidAgeError("Age cannot be negative.")
if age < 18:
raise UnderageError(age)
return "Access granted."
try:
check_age(15)
except UnderageError as e:
print(e) # Age 15 is below minimum 18.Practical Exercise
Create a custom exception: class MyError(Exception): pass
Raise it: raise MyError('Something went wrong')
Catch it: except MyError as e: print(e)
Create a subclass with extra attributes
Key Takeaways
- Custom exceptions: subclass Exception.
- class MyError(Exception): pass is enough.
- Add custom __init__ for extra info.
- Build hierarchies: UnderageError(InvalidAgeError).
- Useful for domain-specific errors (InvalidAgeError, InsufficientFundsError).
Comments
Comments
Post a Comment