Errors & debugging
Medium
Raise a clear custom error
Validate input early and raise ValueError with a helpful message.
How it works
Validate function inputs at the boundary — fail fast with a message that explains the fix.
raise ValueError('...') is appropriate for bad arguments that callers can correct.
Document expected types and ranges in the docstring so IDE hints and readers stay aligned.
def positive_only(n):
"""Return n if it is strictly positive."""
if n <= 0:
raise ValueError(f"Expected a positive number, got {n}")
return n
print(positive_only(5))
try:
positive_only(-1)
except ValueError as exc:
print(exc)
Sponsored
Sponsored
Reserved space — layout preview until AdSense is connected