Custom error messages
📖 Scenario: You are creating a simple program that asks a user to enter their age. You want to make sure the age is a positive number. If the user enters a wrong value, you will show a clear custom error message to help them understand the mistake.
🎯 Goal: Build a program that checks the user's age input and shows a custom error message if the input is not a positive number.
📋 What You'll Learn
Create a variable called
age_input with the value '-5' (a string).Create a variable called
error_message with the value 'Age must be a positive integer.'.Write a
try block that converts age_input to an integer called age.If
age is less than or equal to zero, raise a ValueError with the error_message.Write an
except block that catches ValueError and prints the error_message.Print
age if no error occurs.💡 Why This Matters
🌍 Real World
Custom error messages help users understand what went wrong and how to fix it, improving user experience in apps and websites.
💼 Career
Many programming jobs require writing clear error handling to make software reliable and user-friendly.
Progress0 / 4 steps