Exceptions signal contract violations cleanly

Beginner Defensive APIs: validation, sanitization & exceptions
Created by Pavel · 29.04.2026 at 19:10 UTC

Return codes like -1 or sentinel strings collide with legitimate data: a temperature of -1 might be real, and the string "none" might be a valid category label. Exceptions separate happy-path returns from failure signalling and carry stack context when uncaught.

In data pipelines, parse JSON, CSV, and query parameters at boundaries; raise ValueError or domain-specific errors when contracts break. Catch narrowly at integration points (try / except ValueError) instead of bare except: which also traps KeyboardInterrupt and SystemExit in Python 2 style habits.

Libraries like Pydantic turn validation failures into structured ValidationError objects—same idea: fail loudly with diagnostic information.

Errors and exceptions tutorial: [1].


Sources

University approvals: 0
Tasks
Question 1

Why is return -1 a poor universal error signal for parse_age(text) in public APIs?

Hint

Sentinel return values collide with real data.

Question 2

What does this pattern risk?

try:
    load_dataset(path)
except:
    return None
Hint

Bare except is overbroad.

Question 3

parse_positive_int(raw: str) -> int: strip whitespace; require all digits after strip; value must be > 0. Else ValueError('bad'). No leading sign.

Hint

Reject empty, non-digit, and non-positive after parsing.

Starter code is prefilled; replace TODO blocks with your solution.
1 test case will be used for grading
Run checks runtime behavior only. Final correctness is evaluated when you submit.
Card Info
  • Topic: Defensive APIs: validation, sanitization & exceptions
  • Difficulty: Beginner
  • Completed: 0 users
Creator
Pavel
Pavel