0%

Errors, Validation, and Debugging · practice

Catch a Specific Exception

Suppose someone six where your program needs a quantity. You already know int("six") raises . This time the program has a useful response available: it can say that no quantity was produced and let its caller decide what to do.

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 the except block.

  • If that conversion raises ValueError, Python runs the matching except ValueError block.

The returns 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 name, a 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;

  • None when 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 text can be converted with int().

  • Return None when 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.