Validate an Age with a Custom Exception
Medium · Errors
A custom exception is a class that inherits from an existing one, for example class InvalidAgeError(ValueError): pass. Because it is a ValueError, code that already catches ValueError keeps working. Use raise ... from None to hide the original error when you replace it with a clearer one.
Define InvalidAgeError (a subclass of ValueError) and write parse_age(text):
- Convert text to an int (spaces around it are fine). If that fails, raise InvalidAgeError("age must be a whole number").
- If the age is not between 0 and 150 (inclusive), raise InvalidAgeError("age must be between 0 and 150").
- Otherwise return the age.
The driver check_age is already written: it returns the age, or the error as text.