Defensive vs contract style
P31.error-handling.02 · Audience: guest, it-ml, language-pro · Prerequisites: Error-handling design
Where do you enforce that inputs are valid? Contract-style code states its preconditions and checks them at the boundary, so the rest of the function can trust its inputs. This module writes those guards — and then asks you to defend the whole design in an interview.
ⓘ Concept: Guard clauses, then trust
State the preconditions as guard clauses that raise a
ValueError on violation — an empty name, a negative age.
Unlike an assert (which -O strips), a raised
error is a permanent guard for real, user-facing validation. Use
assert only for internal invariants you consider
impossible.
Why it matters — Validating at the boundary means the body is simpler and every later line can assume good input — the failure happens where the fix is obvious.
Ask the mentor about this module
Ask a question about this content. The mentor explains and grounds its answer in what you are studying; asking is recorded as a learning signal, not a grade.
🎓 Practice ladder
2 graded rungs · ~18 minEnforce preconditions with guard clauses, then defend your error-handling design in an interview.
Rung 1 — preconditions: validate at the door
Loading exercise…
Rung 2 — error-handling design: EAFP, chaining, raise vs return (interview)
Loading exercise…
Types and errors keep one module correct. The last track is how a whole team keeps its code consistent — linting as a contract.
Where next?
Go up a level