Keyboard Shortcuts N Next post
P Previous post
S Save / unsave
R Read aloud
T Toggle theme
/ Focus search
Esc Close panels
🔥
Ready to read...
errors Module 6 - File Handling & Errors Python Python Basics Python Programming: From Zero to Real-World Applications

Custom Exceptions in Python

Reviewed & accurate
AI Summary

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).
Previously: Lesson 39 covered try/except.
Today: You learned: Create your own exception types.
Next: Lesson 41 covers context managers.
Test Your Knowledge
How did you find this?

Comments

Join the discussion! Sign in with your Google or Blogger account, or comment as Anonymous - no account needed. For quick questions, also reach me on Telegram @cytestch.

Comments