Collect several errors

MediumException Handling Programs · 19 of 20

Write a Python program that validates several fields and reports every error at once.

Advertisement
Output
valid
3 errors: name is required; email is invalid; age must be 18-120

Approach

  1. Collect messages in a list and raise one exception at the end.

Solution

Python
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.

More exception handling programs

← All 20 Exception Handling Programs

Leave a Comment