0
0
Pythonprogramming~15 mins

Custom error messages in Python - Mini Project: Build & Apply

Choose your learning style9 modes available
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
1
Create the input variable
Create a variable called age_input and set it to the string '-5'.
Python
Need a hint?

Use age_input = '-5' to create the variable.

2
Create the error message variable
Create a variable called error_message and set it to the string 'Age must be a positive integer.'.
Python
Need a hint?

Use error_message = 'Age must be a positive integer.' to create the variable.

3
Add the try block and check age
Write a try block that converts age_input to an integer called age. Then check if age is less than or equal to zero. If yes, raise a ValueError with the error_message.
Python
Need a hint?

Use age = int(age_input) inside the try block. Then check if age <= 0 and raise ValueError(error_message).

4
Add except block and print age
Add an except ValueError block that prints the error_message. After the try-except, print the variable age if no error occurs.
Python
Need a hint?

Use except ValueError: and inside it print(error_message). Use else: to print age if no error.