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
BeginnerImplement 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")
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Python for C# Developers
1C# Foundations in Python
Run the Python WorkspaceOutput, Strings, and CommentsTyped Locals to Python NamesDivision and RemaindersIndentation Instead of BracesRecap: Port a Receipt4Loops and Transformations
From foreach to forIndexes and Dictionary ItemsSentinels and Loop ControlFrom LINQ to ComprehensionsRecap: Stable Ranking2None and Decisions
Nullable Values and NoneEquality, Identity, and TypesTruth Tests and FallbacksBranch PriorityRecap: Eligibility Rules3Collections and References
From List<T> to listTuples and UnpackingDictionary Keys and ValuesSets, Aliases, and CopiesRecap: Stock Lookup6Reliable Python Programs
Input and Exact OutputExceptions and ValidationImports and the Main GuardType Hints and Runtime TypesRecap: Validate a Batch9Project: Order Processor
Project 1: Order ModelProject 2: Pricing PoliciesPractice on your own: Online Python compiler