Errors and try/except
An exception stops normal flow and travels up the call stack until something handles it.
def to_int(text):
try:
return int(text)
except ValueError:
return Nonetryholds the code that might fail.except SomeErrorhandles only that type, and its subclasses.elseruns if nothing was raised.finallyalways runs, which suits cleanup.
Catch what you expect
A bare except: or a wide except Exception: also hides your own bugs. Name the exact error you know how to handle and let the rest propagate.
Raising
def set_age(age):
if age < 0:
raise ValueError(f"bad age: {age}")
return ageUse except (ValueError, TypeError): for several types at once. Python 3.14 also accepts that without the parentheses, when there is no as clause.
Your task
Write parse_age(text) converting text to an int and raising ValueError if it is not a number or is outside 0 to 150. Write safe_ratio(a, b) returning a / b, or None when b is zero. Other errors must still propagate.
The explanation opens here once every check passes.