added error handling
This commit is contained in:
1 parent
7bf4ab96ed
commit
8f4f08b8a6
2 files changed
+194
No files matched your search
@@ -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}")
|
||||
Reference in new issue
Block a user