Python Programming from First Principles: Learn to Code, Think Computationally, and Solve Real-World Problems
PDFEPUB
BOOK 000 · CHAPTER 8 · Exercise 2 — Student Registration Validator (Raising & Custom Exceptions)

Exercise 2 — Student Registration Validator (Raising & Custom Exceptions)

Scenario

A university registration system must validate new student entries before they are stored. Invalid names, incorrect age formats, or unrealistic age values can easily slip into the database unless the system performs strict checks. Your task is to create a small validation function that raises meaningful custom exceptions whenever the input violates these rules.

Task

Define a custom exception named RegistrationError. Then write a function register_student(name, age) that checks whether the provided name is non-empty, whether the age can be interpreted as an integer, and whether the resulting age falls within the exercise’s assumed range of 16 to 120 inclusive. A name containing only whitespace is empty. Accept integers or integer text, and reject fractional values rather than truncating them. These are exercise rules, not a claim about every university’s admission policy. If any of these rules are broken, the function should raise RegistrationError with an appropriate message. When the data is valid, the function should return a confirmation message. The test loop attempts to register several students, catching and displaying any registration problems.

Starter Code

class RegistrationError(Exception):
    pass

def register_student(name, age):
    # TODO: raise RegistrationError in all invalid cases
    pass

students = [
    ("Alice", 20),
    ("", 19),
    ("Bob", "twenty"),
    ("Clara", 150),
]

for name, age in students:
    try:
        print(register_student(name, age))
    except RegistrationError as e:
        print("Registration failed:", e)
Listing 402 — Exercise 2 — Student Registration Validator (Raising & Custom Exceptions)

Example Output

Student Alice (20) registered.
Registration failed: Name cannot be empty.
Registration failed: Age must be an integer.
Registration failed: Age must be between 16 and 120.