ValueError occurs when an operation receives an argument of the right type but an unsuitable value. A common case is converting a numeric-looking string whose contents are invalid: int("3#") receives a string but cannot interpret its value as an integer. section 12.3
Handling invalid task data
A task parser can catch the conversion failure explicitly: try: urgency = int(urgency_str) except ValueError as ex: print(f"Couldn't cast the number. Description: {ex}") return None For input "Laundry,3#", Python reports: invalid literal for int() with base 10: '3#'. A user-facing application could display a warning and request corrected data instead of stopping. section 12.3 section 12.3.4
ValueError also appears when valid operations cannot use a requested value:
- list.remove(item) raises ValueError when the item is absent. section 3.1.1
- sequence.index(item) raises ValueError when no matching item exists. section 4.3.5
- Handle the specific exception rather than using a broad catch; run the potentially failing operation during development to identify the appropriate exception. section 12.3.6
Listing 12.12 Creating a variable from the exception
def process_task_string6(text):
title, urgency_str = text.split(",")
try:
urgency = int(urgency_str)
except ValueError as ex:
print(f"Couldn't cast the number. Description: {ex}")
return None
task = Task(title, urgency)
return task
Shows a complete task-processing function that catches ValueError, binds it to ex, reports its details, and returns None. section 12.3.4
