-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcustom_exceptions.py
More file actions
294 lines (221 loc) · 8.1 KB
/
Copy pathcustom_exceptions.py
File metadata and controls
294 lines (221 loc) · 8.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
"""
Module: custom_exceptions.py
Topic: Creating Custom Exceptions
Level: Intermediate
This file teaches you about:
- Creating custom exception classes
- Exception hierarchy
- Adding custom attributes
- Best practices for custom exceptions
"""
# =============================================================================
# SECTION 1: BASIC CUSTOM EXCEPTION
# =============================================================================
print("=" * 60)
print("BASIC CUSTOM EXCEPTION")
print("=" * 60)
class CustomError(Exception):
"""A simple custom exception."""
pass
try:
raise CustomError("Something went wrong!")
except CustomError as e:
print(f" Caught: {e}")
# =============================================================================
# SECTION 2: EXCEPTION WITH CUSTOM ATTRIBUTES
# =============================================================================
print("\n" + "=" * 60)
print("EXCEPTION WITH CUSTOM ATTRIBUTES")
print("=" * 60)
class ValidationError(Exception):
"""Exception raised for validation errors."""
def __init__(self, message, field=None, value=None):
super().__init__(message)
self.field = field
self.value = value
def __str__(self):
result = super().__str__()
if self.field:
result = f"[{self.field}] {result}"
return result
def validate_user(username, age):
"""Validate user data."""
if not username or len(username) < 3:
raise ValidationError("Username too short", field="username", value=username)
if age < 0 or age > 150:
raise ValidationError("Invalid age", field="age", value=age)
return True
try:
validate_user("ab", 25)
except ValidationError as e:
print(f" Error: {e}")
print(f" Field: {e.field}")
print(f" Value: {e.value}")
# =============================================================================
# SECTION 3: EXCEPTION HIERARCHY
# =============================================================================
print("\n" + "=" * 60)
print("EXCEPTION HIERARCHY")
print("=" * 60)
# Base exception for our application
class AppError(Exception):
"""Base exception for application errors."""
pass
# Database-related exceptions
class DatabaseError(AppError):
"""Base exception for database errors."""
pass
class ConnectionError(DatabaseError):
"""Database connection failed."""
pass
class QueryError(DatabaseError):
"""Database query failed."""
pass
# API-related exceptions
class APIError(AppError):
"""Base exception for API errors."""
pass
class AuthenticationError(APIError):
"""Authentication failed."""
pass
class RateLimitError(APIError):
"""Rate limit exceeded."""
def __init__(self, message, retry_after=None):
super().__init__(message)
self.retry_after = retry_after
# Handle different exception types
def handle_error(error):
"""Handle errors based on their type."""
if isinstance(error, ConnectionError):
return "Database connection issue"
elif isinstance(error, QueryError):
return "Database query issue"
elif isinstance(error, AuthenticationError):
return "Authentication failed"
elif isinstance(error, RateLimitError):
return f"Rate limited. Retry after {error.retry_after}s"
elif isinstance(error, DatabaseError):
return "Generic database error"
elif isinstance(error, APIError):
return "Generic API error"
elif isinstance(error, AppError):
return "Generic application error"
else:
return "Unknown error"
# Test the hierarchy
errors = [
ConnectionError("Cannot connect to DB"),
RateLimitError("Too many requests", retry_after=60),
AuthenticationError("Invalid token"),
]
print("Error handling:")
for error in errors:
print(f" {type(error).__name__}: {handle_error(error)}")
# =============================================================================
# SECTION 4: PRACTICAL EXAMPLE - VALIDATION FRAMEWORK
# =============================================================================
print("\n" + "=" * 60)
print("PRACTICAL EXAMPLE - VALIDATION FRAMEWORK")
print("=" * 60)
class ValidationException(Exception):
"""Base validation exception."""
def __init__(self, errors):
"""
Initialize with a list of errors.
Args:
errors: List of (field, message) tuples
"""
self.errors = errors
super().__init__(self._format_errors())
def _format_errors(self):
return "; ".join(f"{field}: {msg}" for field, msg in self.errors)
class Validator:
"""A simple validation framework."""
def __init__(self):
self.errors = []
def required(self, value, field):
"""Check if value is not empty."""
if value is None or value == "":
self.errors.append((field, f"{field} is required"))
return self
def min_length(self, value, field, min_len):
"""Check minimum length."""
if value and len(value) < min_len:
self.errors.append((field, f"{field} must be at least {min_len} characters"))
return self
def max_length(self, value, field, max_len):
"""Check maximum length."""
if value and len(value) > max_len:
self.errors.append((field, f"{field} must be at most {max_len} characters"))
return self
def email(self, value, field):
"""Validate email format."""
import re
pattern = r'^[\w.-]+@[\w.-]+\.\w+$'
if value and not re.match(pattern, value):
self.errors.append((field, f"{field} must be a valid email"))
return self
def range(self, value, field, min_val, max_val):
"""Check if value is within range."""
if value is not None and (value < min_val or value > max_val):
self.errors.append((field, f"{field} must be between {min_val} and {max_val}"))
return self
def validate(self):
"""Raise exception if there are errors."""
if self.errors:
raise ValidationException(self.errors)
return True
# Using the validation framework
def create_user(username, email, age):
"""Create a user with validation."""
validator = Validator()
validator.required(username, "username").min_length(username, "username", 3)
validator.required(email, "email").email(email, "email")
validator.range(age, "age", 0, 120)
validator.validate()
# If we get here, validation passed
return {"username": username, "email": email, "age": age}
# Test validation
test_cases = [
("ab", "invalid", 200), # Multiple errors
("valid_user", "test@example.com", 25), # Valid
]
for username, email, age in test_cases:
try:
user = create_user(username, email, age)
print(f" Created: {user}")
except ValidationException as e:
print(f" Validation failed: {e}")
# =============================================================================
# SECTION 5: CONTEXT MANAGER FOR EXCEPTIONS
# =============================================================================
print("\n" + "=" * 60)
print("CONTEXT MANAGER FOR EXCEPTIONS")
print("=" * 60)
class ErrorCollector:
"""Collect errors without raising exceptions."""
def __init__(self):
self.errors = []
def __enter__(self):
return self
def __exit__(self, exc_type, exc_val, exc_tb):
if exc_type is not None:
self.errors.append((exc_type.__name__, str(exc_val)))
return True # Suppress the exception
return False
def has_errors(self):
return len(self.errors) > 0
# Using the error collector
print("Error collector:")
with ErrorCollector() as collector:
result = 10 / 0 # This won't crash
if collector.has_errors():
print(f" Errors collected: {collector.errors}")
# =============================================================================
# MAIN EXECUTION
# =============================================================================
if __name__ == "__main__":
print("\n" + "=" * 60)
print("✅ You've learned about custom exceptions!")
print("📚 Next: Move to advanced features module")
print("=" * 60)