03 / REUSABLE LOGIC · LESSON 12

Validate input and handle errors

Reject invalid memory values without hiding programming mistakes.

13 min · learn at your pace

Fail where the problem starts

A conversion can fail: int("eight") raises ValueError. A conversion can also succeed while the value violates your rule: int("-8") is an integer, but negative memory is not valid for this exercise. Check both the representation and the allowed range.

raise ValueError("Memory must be positive") makes that failure explicit. A function should either return the promised value or report why it cannot. Returning zero for every bad input would make malformed records look like real zero-capacity devices.

Catch the errors you expect

A try block contains work that may fail. An except ValueError block handles that particular failure. Catching every exception with a bare except can hide unrelated bugs and interrupts. Keep the protected block small so it is clear what failed.

The caller can decide to record the bad row and continue. A finally block runs for cleanup whether the work succeeds or fails; for files, a with statement usually manages cleanup more clearly. In your function, keep validation separate from printing so another tool can reuse it.

Try an example.py
def parse_count(text):
    count = int(text)
    if count < 0:
        raise ValueError("Count cannot be negative")
    return count

try:
    print(parse_count("bad"))
except ValueError as error:
    print(f"Check the input: {error}")
YOUR TURN

Put it into practice.

Define parse_memory(text). Convert a string to an integer and return it only when it is at least 1. Raise ValueError for zero, negative, fractional, empty, or nonnumeric strings. Do not print inside the function.

See an explained solution
One way to solve it.py
def parse_memory(text):
    value = int(text)
    if value < 1:
        raise ValueError("Memory must be at least 1 GB")
    return value

int handles representation errors, and the range check handles a valid integer that violates the contract. Both failures use ValueError so callers can handle them consistently.