Python Practice › Exception Handling Programs › Program 9
Raise an exception
Write a Python function that raises ValueError for an invalid age.
Input
25, -3
Output
age set: 25 rejected: age must be positive, got -3
Approach
raise ValueError("message").
Solution
def set_age(age): if age < 0: raise ValueError(f"age must be positive, got {age}") return age for a in [25, -3]: try: print("age set:", set_age(a)) except ValueError as e: print("rejected:", e)Output
age set: 25 rejected: age must be positive, got -3
Learn the concept
New to this topic? Read the lesson, then come back.