Python Mastery – From Basics to Brilliance / Exception Handling

Real-time Example: User Age Validator

Let’s build a small utility that validates age:

def validate_age():
    try:
        age = int(input("Enter your age: "))
        if age < 0:
            raise ValueError("Age must be a positive number")
        elif age < 18:
            print("You are a minor.")
        else:
            print("You are an adult.")
    except ValueError as ve:
        print("Invalid input:", ve)
    finally:
        print("Validation complete.")

validate_age()
Enter your age: -5
Invalid input: Age must be a positive number
Validation complete.