Guard clauses before brittle arithmetic

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

Division, logarithms, and normalisations explode on zero or negative values in the wrong domain. Guard clauses at the top of a function (if denom == 0: raise ValueError) document preconditions and avoid try/except around expected business violations.

In notebooks, silent inf and nan from bad divides propagate into metrics—guarding early keeps plots trustworthy.

This pairs with numpy conventions: np.where masks, divide with where=, or explicit checks before log.

Floating-point exceptions in NumPy: [1].


Sources

University approvals: 0
Tasks
Question 1

Best practice before ratio = hits / total in a reporting API when total may be zero:

Hint

Explicit policy beats accidental inf.

Question 2

Compared with catching ZeroDivisionError after dividing, a guard clause before dividing primarily improves:

Hint

Expected errors can be explicit branches.

Question 3

safe_ratio(top, bot) returns top/bot; if bot == 0, raise ValueError('zero').

Hint

Check denominator first.

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