Defensive vs contract style
P31.error-handling.02 · Audience: Guest, IT/ML learner, Language professional · Prerequisites: Error-handling design
Where next?
Go up a level
P31.error-handling.02 · Audience: Guest, IT/ML learner, Language professional · Prerequisites: Error-handling design
Go up a level
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.
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 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.
Off by default. The mentor always gets your file; this only decides whether your own copy stays here. Copies live in this browser only - they do not follow you to another device, and clearing site data removes them.
Enforce preconditions with guard clauses, then defend your error-handling design in an interview.
Loading exercise…
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.
Loading your notes...