Date Constructor Rejects Impossible Dates
date(year, month, day) validates on construction: impossible dates raise ValueError with the exact rule instead of rolling into the next month.
Code
from datetime import date
# date validates its components at construction time: impossible
# dates raise ValueError naming the broken rule instead of rolling
# over into the next month
def load_date(year, month, day):
try:
return date(year, month, day)
except ValueError as error:
return f'rejected: {error}'
print(load_date(2026, 11, 21))
print(load_date(2026, 2, 30)) # February never has 30 days
print(load_date(2025, 13, 1)) # months run 1..12
print(load_date(2025, 3, 0)) # days run 1..31
print(load_date(2024, 2, 29)) # leap year accepts Feb 29
print(load_date(2025, 2, 29)) # non-leap year rejects itOutput
Captured from a sandboxed run of this snippet in the build pipeline.
2026-11-21
rejected: day is out of range for month
rejected: month must be in 1..12
rejected: day is out of range for month
2024-02-29
rejected: day is out of range for monthHow it works
The whole behavior is carried by the function load_date.
A ValueError is raised unconditionally at its raise site — no input check sits in front of it.
What to watch for
- No packages pulled in; the language’s built-in APIs carry all of the work here.
Using it
Entry signature: def load_date(year, month, day)
load_date is the public entry point; everything else in the file exists to support it.
The key statements, annotated
def load_date(year, month, day):
try:
return date(year, month, day)
except ValueError as error:
return f'rejected: {error}'
Interactive Tools for This Topic
JSON to Zod Schema ConverterInfer typed Zod z.object schemas from JSON payloads locally, supporting nested objects, merged array shapes, enums, nullable fields, and JSDoc comments.JSON Schema ValidatorValidate JSON data against a JSON Schema definition and get detailed error reports. Supports type checking, required fields, and common constraint validation.JSONL / NDJSON InspectorValidate NDJSON and JSON Lines line-by-line, pinpoint syntax errors by line number, analyze key frequencies and types, and export a pretty JSON array.Age CalculatorCalculate exact age in years, months, and days between a birth date and a reference date, plus total days and the next birthday countdown.
FAQ
- What triggers the exception?
- No. The `ValueError` is not behind any guard — it triggers purely on reaching that line of code.
- Does the code pull in any external packages?
- No external packages are involved; every call resolves to a built-in API. The file defines `load_date` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.