Sponsored Reserved space — layout preview until AdSense is connected

Raise a clear custom error

Validate input early and raise ValueError with a helpful message.

12 lines 3 views 1 copies Updated May 23, 2026
Try in editor

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.

Python
Try in editor
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

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Errors & debugging