L2 · Working engineerPython internals~4 min · 6 tests#63

Create and Raise a Custom Exception

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

  1. Define InvalidAgeError, a subclass of ValueError.
  2. Write validate_age(age) that returns age when it is between 0 and 150 inclusive, and otherwise raises InvalidAgeError with a helpful message.

Examples

  1. Example 1

    Input

    raises(validate_age, -5)

    Expected output

    'InvalidAgeError'
  2. 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/3

    How an interviewer scores this

    0/9
    Python 3.13 · validate_age
    ⌘/Ctrl + Enter runs the examples

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

    Time complexity of the optimal solution
    Space complexity (extra memory)

    Pick both to reveal the answer.

    From brute force to optimal

    The progression an interviewer wants to hear, one step at a time.

    ApproachTimeSpaceIdea
    Subclass a built-in exceptionO(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?