Define a custom Python exception class, raise it for invalid input and test it with try/except. Learn exception hierarchies with live tests.
The problem
- Define
InvalidAgeError, a subclass ofValueError. - Write
validate_age(age)that returnsagewhen it is between0and150inclusive, and otherwise raisesInvalidAgeErrorwith a helpful message.
Examples
Example 1
Input
raises(validate_age, -5)
Expected output
'InvalidAgeError'
Example 2
Input
validate_age(30)
Expected output
30
+ 4 hidden tests on Submit — part of the ValueError family.
Edge cases to ask about
- Boundaries 0 and 150
- Negative age
Hints
0/3How an interviewer scores this
0/9Your code runs in real CPython inside your browser — nothing is sent anywhere. The first run downloads the interpreter (about 6 MB, once). Your code is saved on this device as you type.
Complexity Lab
What does this cost as n grows?
Interviewers score the analysis as much as the code. Commit to an answer first — then check it, and read why.
Pick both to reveal the answer.
From brute force to optimal
The progression an interviewer wants to hear, one step at a time.
| Approach | Time | Space | Idea |
|---|---|---|---|
| Subclass a built-in exception | O(1) | O(1) | Subclassing ValueError lets callers catch either. |
Walkthrough of the optimal approach (try it yourself first)
Subclass the closest built-in (ValueError for bad values) so callers can catch your specific error or the general family. Include the bad value in the message — it is the first thing someone debugging needs.
Never subclass BaseException directly; that is reserved for things like KeyboardInterrupt.
Complexity: O(1) time, O(1) space. A constant-time comparison.
Reveal the reference solution
class InvalidAgeError(ValueError): """Raised when an age is outside 0–150.""" def validate_age(age): if not 0 <= age <= 150: raise InvalidAgeError(f"age must be between 0 and 150, got {age}") return age
Follow-ups interviewers ask
- Add a custom attribute (the bad value) to the exception.
- What does
raise … from …do?
Frequently asked interview questions
Core interview concepts, complexities, and follow-ups scored by hiring teams.
What is the time complexity of Create and Raise a Custom Exception in Python?
The optimal solution runs in O(1) time and O(1) auxiliary space. A constant-time comparison.
What follow-up questions do interviewers ask about Create and Raise a Custom Exception?
Add a custom attribute (the bad value) to the exception. What does raise … from … do?
