Errors and debugging
Raise clear errors for invalid values
Validate inputs and raise ValueError when a value is outside the expected range.
Lesson 36 of 63
Reading: about 2 min
Lesson + practice: about 13 min
Difficulty: Beginner
On this page4 sections
Some inputs have the right type but still make no sense for a task. A study duration of zero or less is an example. Type hints do not enforce types at runtime, so check the exact type as well as the range. type(value) is int rejects strings and Boolean values; raise stops the operation with a useful exception.
def positive_minutes(value: int) -> int:
"""Return a positive integer duration or raise ValueError."""
if type(value) is not int or value <= 0:
raise ValueError("minutes must be a positive integer")
return value
print(positive_minutes(25))25
Handle it at the right boundary
The caller can catch the specific ValueError and show a friendly message. The validation function itself stays focused on checking its rule.
def positive_minutes(value: int) -> int:
if type(value) is not int or value <= 0:
raise ValueError("minutes must be a positive integer")
return value
try:
positive_minutes(0)
except ValueError as error:
print(error)minutes must be a positive integer
Why this works
Parsing and validation answer different questions. int("0") parses successfully because 0 is an integer, but a positive-duration rule rejects it. The exact type check also rejects True, which otherwise behaves like an integer in comparisons. raise ValueError communicates that the value is unsuitable; a caller can catch it.
Practice
Write a function that requires a positive integer session count. Test it with 3, 0, and True, catching the error for the two invalid values at the call site.
Why raise ValueError for zero minutes here?
Reveal answer
Zero is an integer, but it violates the function’s positive-duration rule.
Try another case
What happens for positive_minutes(-5) and positive_minutes(True)?
Check your answer
Reveal answer
Both raise ValueError: -5 is not positive, and True is not exactly an int.
Your progress
Reveal the check answer or reach the end to complete this lesson.