Exceptions and Resource Scope
Lesson 28 of 48 in Coddy's Python for Kotlin Developers course.
Kotlin toInt throws NumberFormatException for malformed input and toIntOrNull offers an optional result. Python int raises ValueError, so catch that specific exception when invalid text is expected. Python raise corresponds to Kotlin throw. Both languages support finally; Kotlin use and Python with address scoped cleanup through different resource protocols. A successful conversion still needs domain-range validation.
Kotlin
fun main() {
try { println("12cats".toInt()) } catch (e: NumberFormatException) { println("invalid") }
}Python
try:
print(int("12cats"))
except ValueError:
print("invalid")Porting trap
Catching every Python exception can hide programming defects. Catch the conversion failure, then reject values outside the permitted capacity range explicitly.
Complete the task in its editable modules. The locked driver.py supplies execution; keep the required API names.
Challenge
BeginnerImplement 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")
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Python for Kotlin Developers
1From Kotlin to Python
Run Your First Python ProgramPrint and String TemplatesVal, Var, and Python NamesDivision and Integer WidthSuites and Block ScopeRecap: Rewrite a Receipt4Iteration and Transformations
Ranges and Loop BindingsEntries and withIndexUpdates and Loop ControlCollection PipelinesRecap: Build a Ranking2Values and Decisions
Nullable Types and NoneEquality and IdentityBoolean Conditions and orIf Expressions and ElifRecap: Eligibility Rules3Collections and Shared State
Read-only Lists and MutationPair and Tuple UnpackingMap Lookup and Missing KeysShallow Copies and SetsRecap: Clean an Inventory6Input, Errors, and Modules
Console Input and FormattingExceptions and Resource ScopeImports and Entry PointsStatic Types and AnnotationsRecap: Validate a Batch9Project: Order Processing
Create the Order ModelAdd Pricing PoliciesPractice on your own: Online Python compiler