Menu
CoddyTech

Exceptions and Validation

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

Separate conversion failures from invalid business values.

C# reference excerpt

Executable statements use C# top-level program style; type-only examples are declarations. System names assume the usual using System directive.

try { int.Parse("bad"); }
catch (FormatException) { Console.WriteLine("invalid"); }

Python

try:
    int("bad")
except ValueError:
    print("invalid")

What changes

Use try/except and raise rather than try/catch and throw. int("bad") raises ValueError; int(None) raises TypeError. TypeError generally signals an inappropriate argument type or operation, while ValueError signals an unacceptable value of an appropriate type. C# parsing can also overflow a fixed-width int; Python integers do not have that same fixed-width bound. Validate business ranges explicitly.

Transfer mistake

Catch expected conversion or business failures, not every Exception. KeyError, AttributeError and ZeroDivisionError convey other failures; swallowing them can hide defects. A function required to raise must not return the string "invalid" instead. An else after try/except runs only if the try suite finishes without an exception.

Your task

Implement parse_capacity(text). Convert using int and return the integer only when it is between 0 and 500 inclusive. Raise ValueError for malformed text or out-of-range values. int accepts surrounding whitespace and a leading plus sign. The driver prints the returned value or invalid when it catches ValueError; silent API checks also reject implementations returning error strings.

challenge icon

Challenge

Beginner

Implement parse_capacity(text). Convert using int and return the integer only when it is between 0 and 500 inclusive. Raise ValueError for malformed text or out-of-range values. int accepts surrounding whitespace and a leading plus sign. The driver prints the returned value or invalid when it catches ValueError; silent API checks also reject implementations returning error strings.

Editable implementation files: functions.py. The locked driver.py is the supplied launcher or input/output harness and must remain unchanged.

Keep the supplied imports and exact API names. Return results or raise the required exceptions; do not read input or print from these implementation modules.

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 C# Developers

Practice on your own: Online Python compiler