Menu
CoddyTech

Exceptions and Validation

Lesson 28 of 48 in Coddy's Python for JavaScript Developers course.

Distinguish invalid data from valid zero and handle only the failures your program expects.

JavaScript

const text = "oops";
const value = Number(text);
if (Number.isNaN(value)) {
  console.log("invalid");
} else {
  console.log(value + 1);
}

Python

text = "oops"
try:
    value = int(text)
except ValueError:
    print("invalid")
else:
    print(value + 1)

What changes

Both examples print invalid for this text, but the conversion APIs are not equivalent for every string. JavaScript Number can produce NaN; Python int raises ValueError for malformed integer text. Python try surrounds operations that may fail. A matching except handles that exception and execution can continue afterward. The optional else block runs only when the try block completes without an exception. Use raise ValueError("message") when parsing succeeds but a value violates your own rule, such as a negative capacity. Raising exits the current path until a matching handler is found. Exception names identify categories: malformed numeric text is different from dividing by zero.

Common mistake

A bare except can hide programming errors and even interruption signals. Catch specific expected types around a small operation. Returning zero for every failure makes invalid input indistinguishable from a legitimate zero. If several failures have different user-facing meanings, keep their handlers separate.

Your task

Build a parser that returns valid capacities and raises a specific exception for invalid ones. The driver converts expected failures into a documented output line.

challenge icon

Challenge

Beginner

Implement parse_capacity(text). Convert the string with int. Accept integers from 0 through 500, inclusive, and return the integer. Raise ValueError for malformed text or out-of-range values. Do not print or read input. The driver reads one line, prints the returned capacity, or prints invalid when ValueError is raised. Surrounding whitespace and a leading plus sign are allowed by integer conversion.

The locked driver also calls your function with invalid arguments to verify the required exceptions. A successful result must be an integer; returning error text does not satisfy the contract. These checks produce no additional output.

Your function definitions go in functions.py. The locked driver.py imports them and handles the supplied input/output and checks. You do not need to edit the driver.

Try it yourself

from functions import parse_capacity

_coddy_line = input()
try:
    _coddy_result = parse_capacity(_coddy_line)
except ValueError:
    print("invalid")
else:
    if type(_coddy_result) is not int:
        raise AssertionError("parse_capacity must return an integer on success")
    print(_coddy_result)
for _coddy_invalid in ("oops", "-1", "501"):
    try:
        parse_capacity(_coddy_invalid)
    except ValueError:
        pass
    else:
        raise AssertionError("parse_capacity must raise ValueError for invalid input")
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Python for JavaScript Developers

Practice on your own: Online Python compiler