all Python 3calendarexception
calendar.IllegalMonthError
exceptions
Raised for a month number outside 1–12; a subclass of ValueError, and in newer versions of IndexError as well. The bad number is in the month attribute.
Syntax
except calendar.IllegalMonthError as e: e.month
Catch it as ValueError: that works on every version. Not every function raises it: weekday(2024, 13, 1) raises a plain ValueError from datetime, and month(2024, 13) failed with IndexError on 3.11 and early 3.12 releases, switching to IllegalMonthError only later. So except calendar.IllegalMonthError misses some bad-month errors.
Examples
import calendar
try:
calendar.monthrange(2024, 13)
except ValueError as e:
print(type(e).__name__, e.month) # → IllegalMonthError 13
import calendar
try:
calendar.weekday(2024, 13, 1)
except calendar.IllegalMonthError:
print('IllegalMonthError')
except ValueError:
print('ValueError') # → ValueError — weekday() бросает обычный
See also
Common errors
Open in the full glossarydocs.python.orgReport an inaccuracy