Errors, Validation, and Debugging · practice
Catch a Specific Exception
Suppose someone six where your program needs a quantity. You already know int("six") raises
That is what try and except express:
def parse_quantity(text):
try:
quantity = int(text)
except ValueError:
return None
return quantity
Read it as a small agreement: try the conversion, and handle this one expected failure if it happens. Python runs the indented try block first.
If
int(text)succeeds, execution skips theexceptblock.If that conversion raises
ValueError, Python runs the matchingexcept ValueErrorblock.
The None to mean “no integer could be produced.” A caller can check that result:
result = parse_quantity("six")
if result is None:
print("No quantity available.")
else:
print(result)
Catch the failure you expect
This code catches ValueError because invalid integer text is an expected situation the function knows how to represent.
It does not catch every possible exception. If the function contains a misspelled NameError should remain visible. Hiding that programming mistake would make debugging harder.
Keep the protected block focused
Put only the operation that may raise the expected exception inside try:
try:
year = int(text)
except ValueError:
return None
A small block makes the connection clear: the handler belongs to that conversion. If many unrelated statements are inside the block, a matching exception from the wrong statement could be mistaken for the anticipated failure.
Handling is part of the function’s contract
Without handling, invalid text stops the program. With this design, the function promises one of two results:
an integer when conversion succeeds;
Nonewhen the text is not an integer.
That is a design choice, not a rule for every program. Sometimes retrying is better. Sometimes an exception should stop the program because the data indicates a genuine programming mistake. Catch an exception only when you can take a meaningful next step.
Why does the example use except ValueError?
Task
Complete parse_year(text).
Return the converted integer when
textcan be converted withint().Return
Nonewhen conversion raises. Catch only
ValueError.
Keep the two prepared calls. The final output must be:
2026
None
After it works, use Step on your completed code to watch the successful call skip the handler and the unsuccessful call enter it.