Raise an exception

EasyException Handling Programs · 9 of 20

Write a Python function that raises ValueError for an invalid age.

Advertisement
Input
25, -3
Output
age set: 25
rejected: age must be positive, got -3

Approach

  1. raise ValueError("message").

Solution

Python
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.

More exception handling programs

← All 20 Exception Handling Programs

Leave a Comment