Python Practice › Exception Handling Programs › Program 19
Collect several errors
Write a Python program that validates several fields and reports every error at once.
Output
valid 3 errors: name is required; email is invalid; age must be 18-120
Approach
- Collect messages in a list and raise one exception at the end.
Solution
class ValidationError(Exception): def __init__(self, errors): super().__init__("; ".join(errors)) self.errors = errors def validate(user): errors = [] if not user.get("name"): errors.append("name is required") if "@" not in user.get("email", ""): errors.append("email is invalid") if not 18 <= user.get("age", 0) <= 120: errors.append("age must be 18-120") if errors: raise ValidationError(errors) return "valid" for user in [{"name": "Asha", "email": "asha@x.com", "age": 29}, {"name": "", "email": "bad", "age": 5}]: try: print(validate(user)) except ValidationError as e: print(len(e.errors), "errors:", e)Output
valid 3 errors: name is required; email is invalid; age must be 18-120
Line by line
Lines 7-14
Every check runs, so the user sees all problems at once instead of one at a time.
Learn the concept
New to this topic? Read the lesson, then come back.