Raising Exceptions
Completed
Write set_age(age) that raises ValueError("age must be 0-150") for an age outside 0–150 and otherwise returns the age. Read ages and print the result or the error message.
Input
Line 1: n. Then n integers.
Output
n lines.
Example
Input
3 25 -1 200
Output
25 age must be 0-150 age must be 0-150
Editor
Python
Hints
raise ValueError("message") stops the function with an error.
except ValueError as err: gives you the exception object.
Solution explanation
Raising exceptions for invalid input lets the caller decide how to handle it.
Show solution
def set_age(age):
if not 0 <= age <= 150:
raise ValueError("age must be 0-150")
return age
for _ in range(int(input())):
try:
print(set_age(int(input())))
except ValueError as err:
print(err)