diff --git a/deep_errorhandling.py b/deep_errorhandling.py new file mode 100644 index 0000000..10191ae --- /dev/null +++ b/deep_errorhandling.py @@ -0,0 +1,63 @@ +# Build a UserDatabase class: + +# __init__ starts with an empty dict _users +# add_user(username, age) — raises ValueError if age is negative, raises TypeError if username isn't a string +# get_user(username) — raises KeyError if user doesn't exist +# delete_user(username) — raises KeyError if user doesn't exist +# Create a custom DuplicateUserError — raised if adding a username that already exists + +class UserDatabase: + + def __init__(self): + self._users = {} + + def add_user(self, username: str, age: int) -> str: + if age < 0: + raise ValueError("Age can't be negative") + if not isinstance(username, str): + raise TypeError("it should be a string") + if username in self._users: + raise DuplicateUserError(f"The user: {username} is already present, please try again") + self._users.update({ + username:age + }) + + return username + + def get_user(self, username:str) -> None: + if username in self._users: + return self._users.get(username) + else: + raise KeyError("no key found for that user") + + def delete_user(self, username) -> None: + if username not in self._users: + raise KeyError("no key found for that user") + else: + del self._users[username] + +class DuplicateUserError(Exception): + + def __init__(self, *args): + super().__init__(*args) + +user_generator_exp = ((name, age) for name, age in [ + ("luffy", 16), + ("luffy", 18), + ("fifth emperor", 19) +]) + +db = UserDatabase() +for name, age in user_generator_exp: + try: + db.add_user(name, age) + except ValueError as e: + print(f"Got a value error as - {e}") + except TypeError as e: + print(f"Got a type error as - {e}") + except DuplicateUserError as e: + print(f"Got a duplicate user error as - {e}") + else: + print(f"added user {name}") + finally: + print("block executed") \ No newline at end of file diff --git a/deep_errorhandling_prettified.py b/deep_errorhandling_prettified.py new file mode 100644 index 0000000..10ee6e1 --- /dev/null +++ b/deep_errorhandling_prettified.py @@ -0,0 +1,131 @@ +""" +Python Error Handling Practice +=============================== +Concepts covered: +1. try / except / else / finally +2. Custom exceptions (DuplicateUserError) +3. Multiple exception types (ValueError, TypeError, KeyError) +4. Raising exceptions with meaningful messages +5. Generator expressions combined with error handling +""" + + +# ============================================================================= +# 1. CUSTOM EXCEPTIONS +# ============================================================================= + +class DuplicateUserError(Exception): + """Raised when attempting to add a username that already exists.""" + + def __init__(self, *args): + super().__init__(*args) + + +# ============================================================================= +# 2. MAIN CLASS — UserDatabase +# Demonstrates: raising ValueError, TypeError, KeyError, DuplicateUserError +# ============================================================================= + +class UserDatabase: + """A simple user database with validation and error handling.""" + + def __init__(self): + self._users = {} + + def add_user(self, username: str, age: int) -> str: + """Add a user. Raises ValueError, TypeError, or DuplicateUserError.""" + if not isinstance(username, str): + raise TypeError("Username must be a string") + if age < 0: + raise ValueError("Age can't be negative") + if username in self._users: + raise DuplicateUserError(f"The user '{username}' already exists") + self._users[username] = age + return username + + def get_user(self, username: str): + """Get a user's age. Raises KeyError if not found.""" + if username not in self._users: + raise KeyError(f"No user found: '{username}'") + return self._users[username] + + def delete_user(self, username: str) -> None: + """Delete a user. Raises KeyError if not found.""" + if username not in self._users: + raise KeyError(f"No user found: '{username}'") + del self._users[username] + + def __repr__(self): + return f"UserDatabase(users={self._users})" + + +# ============================================================================= +# 3. TESTS — try / except / else / finally with generators +# ============================================================================= + +if __name__ == "__main__": + + # --- Batch add users with generator expression --- + print("=== Adding Users (Generator + Error Handling) ===") + + db = UserDatabase() + + user_gen = ((name, age) for name, age in [ + ("luffy", 16), + ("luffy", 18), # duplicate — should fail + ("zoro", 21), + ("fifth emperor", 19), + ]) + + for name, age in user_gen: + try: + db.add_user(name, age) + except ValueError as e: + print(f" ValueError: {e}") + except TypeError as e: + print(f" TypeError: {e}") + except DuplicateUserError as e: + print(f" DuplicateUserError: {e}") + else: + print(f" Added '{name}', age {age}") + finally: + print(f" Users so far: {len(db._users)}") + + # --- Test bad inputs --- + print("\n=== Bad Inputs ===") + + bad_inputs = ((123, 20), ("nami", -5)) + + for username, age in bad_inputs: + try: + db.add_user(username, age) + except (ValueError, TypeError) as e: + print(f" Rejected: {e}") + + # --- Test get_user --- + print("\n=== Get User ===") + + for name in ("luffy", "unknown"): + try: + age = db.get_user(name) + except KeyError as e: + print(f" Not found: {e}") + else: + print(f" Found '{name}', age {age}") + + # --- Test delete_user --- + print("\n=== Delete User ===") + + for name in ("zoro", "zoro"): + try: + db.delete_user(name) + except KeyError as e: + print(f" Can't delete: {e}") + else: + print(f" Deleted '{name}'") + finally: + print(f" Users remaining: {len(db._users)}") + + # --- Final state --- + print(f"\n=== Final State ===") + print(f" {db}") \ No newline at end of file