COGNITION FOUNDRYLEARN. BUILD. UNDERSTAND.
PY-017 / Handle imperfect input◷ 23 min read + practice

Validation and exceptions

Input is not always what a program expects. If a value cannot be converted or violates a rule, Python raises an exception. Instead of hiding every error, we can handle expected problems and leave genuine defects visible.

By the end, you can: Catch expected ValueError cases narrowly and raise useful exceptions when a function receives invalid input.
Before this lesson: PY-015 · PY-008

An exception explains why work could not continue

int("seven") raises ValueError because the text is not a valid integer. An index outside a list can raise IndexError. A missing name raises NameError. The exception type and traceback help locate the failing operation.

The playground displays these failures so you can learn from them. An exception is not always evidence of a badly designed program: rejecting an invalid input can be precisely the correct behaviour.

Catch only a failure you know how to handle

Put the risky operation inside try; place the recovery in a matching except ValueError: block. Keep the try block small so that the handler cannot accidentally swallow an unrelated problem.

Do not use except: as a universal answer. A broad handler can hide mistakes, interrupts or configuration failures. Start with the specific exception that the operation documents.

Validate business rules separately

Conversion only checks that a value has the right shape. A percentage of 250 is a valid integer but may be invalid for a percentage field. A function can raise ValueError("Percentage must be between 0 and 100") when the rule is broken.

Put rules near the function that depends on them. Then every caller — tutorial, online tool or future application — receives consistent behaviour instead of duplicating the rule in a button click.

Show clear errors at the right boundary

A reusable helper should usually return a useful value or raise a meaningful exception. A user-facing program decides how to present that error. One interface might show red validation text; a command-line program might print a concise explanation.

When testing, exercise valid input, invalid text and boundary values. Do not confuse catching an error with successfully recovering from it: the result should still tell the learner what needs fixing.

Try it yourself.

Choose a starting example or write something completely different. You control the code; the Run button executes what is in the editor, not a hidden preset.

CF Python PlaygroundBrowser-based Python
Ready to load Python
Catch a bad conversion

Keep the script working when one string is not an integer.

Syntax colours highlight Python code. Tab inserts four spaces; press Escape then Tab to leave the editor. Ctrl+Enter runs the current code.
OUTPUT / ERRORS
Press Run Python to execute the editable code.
NOW MAKE IT YOURS

Add "3.5" to the list. Does int() accept that string?

Need a hint?

A decimal-looking string does not convert directly to int.

On first Run, a pinned Python runtime downloads from jsDelivr. Code executes locally in your browser's Web Worker, not on our server. It cannot inspect your normal PC files or Windows hardware. Avoid entering secrets. Heavy/infinite loops are stopped by a time limit.

Check your understanding.

Try answering each question before opening its reference answer. Explain the idea aloud or change an example to test it for yourself.

  1. When is a specific except ValueError preferable to a bare except: handler?

    View answer

    A specific except ValueError handles a known input failure such as invalid integer text while allowing unrelated programming bugs to produce a traceback for diagnosis. A bare except: catches far more, including important interruptions, and can make a broken program appear to succeed. Keep the try block focused on the operation whose failure you understand.

  2. Why might an application need to validate a converted number even after int(text) has succeeded?

    View answer

    Successful conversion only proves that the value could be represented as an integer; it does not prove the value is acceptable for the task. For example, int("250") succeeds, but a discount percentage may need to be between 0 and 100. Separate validation checks enforce that domain rule and can raise a clear ValueError when a valid number is nevertheless inappropriate.

Where this leads.

Now that our helpers can return values and report errors, we can organise related functionality and write small repeatable tests.