Error Codes Versus Exceptions
Lesson 28 of 48 in Coddy's Python for C Developers course.
C APIs commonly return status codes and place successful results through output pointers. Python can return the successful value and raise an exception for invalid input. int raises ValueError for malformed numeric text; a deliberately rejected range can raise the same documented exception. Catch a specific exception around the operation that is allowed to fail. An unrelated TypeError may signal a programming error and should not silently become a validation result.
C: complete example.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdarg.h>
int nonnegative(int value, int *out) { if (value < 0) return 0; *out = value; return 1; }
int main(void) {
int result = 0;
int ok = nonnegative(-2, &result);
printf("%d %d\n", ok, result);
return 0;
}Python: complete example.py
def nonnegative(value):
if value < 0:
raise ValueError("negative")
return value
try:
print(nonnegative(-2))
except ValueError:
print("invalid")Watch the difference
A return string saying invalid is not interchangeable with raising ValueError when the caller relies on exception handling. Validate before changing state so a failed operation leaves the object intact.
Your code goes in functions.py. The locked driver.py is the entry file, supplies execution and checks, and cannot be edited.
Challenge
BeginnerImplement parse_capacity(text), using int conversion and accepting 0..500 inclusive. Return an int or raise ValueError for malformed strings and out-of-range numbers. Whitespace and a leading plus sign are valid. The driver handles printing and checks error behavior separately without more input.
Implement the named definitions in the editable modules without input or printing. The driver owns input/output and may call the APIs again on fresh data without producing extra output.
Use the documented Python exception instead of returning a C-style status code or error string.
Your code goes in functions.py. The locked driver.py is the entry file, supplies execution and checks, and cannot be edited.
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
1From C Programs to Python
Run Python Without mainPrinting Without Format CodesNames Versus Typed StorageDivision and Integer LimitsSuites Instead of BracesRecap: A Python Receipt4Iteration and Transformations
Iteration Without PointersIndexes Without Pointer MathSentinels and Loop ControlComprehensions and SortingRecap: Stable Ranking2Values and Truth Tests
Absence Is Not a Null PointerContent Versus Object IdentityTruth Tests and OperandsConditional Value SelectionRecap: Missing or Eligible3Containers and Aliasing
Lists Versus C ArraysTuples and Struct ValuesMappings and Lookup LoopsPointers, Copies, and AliasesRecap: Inventory Collections6Contracts, Errors, and Modules
Text Input and Exact OutputError Codes Versus ExceptionsImports Are Not IncludesAnnotations Versus C TypesRecap: Validate a Batch9Project: An Order Processor
Project: Model an OrderProject: Pricing PoliciesPractice on your own: Online Python compiler