Jump into concepts and practice - no test required
or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
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
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
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
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
Hint
Use except ValueError: and inside it print(error_message). Use else: to print age if no error.
Practice
(1/5)
1. What is the main purpose of using raise ValueError('Custom message') in Python?
easy
A. To print a warning message without stopping the program.
B. To stop the program and show a specific error message when a condition is not met.
C. To automatically fix errors in the code.
D. To ignore errors and continue running the program.
Solution
Step 1: Understand the raise statement
The raise keyword is used to stop the program and throw an error.
Step 2: Purpose of custom messages
Adding a message like 'Custom message' helps explain why the error happened.
Final Answer:
To stop the program and show a specific error message when a condition is not met. -> Option B
Quick Check:
raise with message = stop and explain error [OK]
Hint: Raise errors to stop and explain problems clearly [OK]
Common Mistakes:
Thinking raise only prints messages without stopping
Confusing raise with print or logging
Believing raise fixes errors automatically
2. Which of the following is the correct syntax to raise a custom error with message "Invalid input"?
easy
A. raise 'Invalid input' ValueError
B. throw ValueError('Invalid input')
C. error ValueError('Invalid input')
D. raise ValueError('Invalid input')
Solution
Step 1: Identify the correct keyword
In Python, raise is used to throw errors, not throw or error.
Step 2: Correct order of error and message
The syntax is raise ErrorType('message'), so the error type comes first, then the message in parentheses.
Hint: If condition fails, raise stops and shows error message [OK]
Common Mistakes:
Expecting function to return 'Access granted' anyway
Confusing error message with print output
Thinking raise prints message but continues
4. Find the error in this code snippet:
def check_number(num):
if num < 0:
raise 'Negative number error'
return 'Number is positive'
print(check_number(-5))
medium
A. You cannot raise a string directly; it must be an Exception type.
B. The raise statement is missing parentheses.
C. The function should return None instead of a string.
D. The if condition should be num > 0.
Solution
Step 1: Check the raise statement
The code tries to raise a string directly, which is not allowed in Python. Only Exception types can be raised.
Step 2: Correct way to raise errors
Use raise ValueError('message') or another Exception class, not a plain string.
Final Answer:
You cannot raise a string directly; it must be an Exception type. -> Option A
Quick Check:
raise must use Exception type, not string [OK]
Hint: Always raise Exception objects, not strings [OK]
Common Mistakes:
Raising strings instead of Exception classes
Forgetting to include parentheses with message
Changing condition incorrectly
5. You want to create a function validate_score(score) that raises a ValueError with the message "Score must be between 0 and 100" if the score is outside this range. Which code correctly implements this?
hard
A. def validate_score(score):
if score < 0 or score > 100:
raise ValueError('Score must be between 0 and 100')
return 'Valid score'
B. def validate_score(score):
if 0 <= score <= 100:
raise ValueError('Score must be between 0 and 100')
return 'Valid score'
C. def validate_score(score):
if score < 0 and score > 100:
raise ValueError('Score must be between 0 and 100')
return 'Valid score'
D. def validate_score(score):
if score == 0 or score == 100:
raise ValueError('Score must be between 0 and 100')
return 'Valid score'
Solution
Step 1: Understand the valid range condition
The score is valid if it is between 0 and 100 inclusive. So invalid means less than 0 or greater than 100.
Step 2: Check the if condition logic
def validate_score(score):
if score < 0 or score > 100:
raise ValueError('Score must be between 0 and 100')
return 'Valid score' correctly uses if score < 0 or score > 100 to detect invalid scores and raise the error.
Final Answer:
def validate_score(score):
if score < 0 or score > 100:
raise ValueError('Score must be between 0 and 100')
return 'Valid score' -> Option A
Quick Check:
Use or for invalid range, raise error if outside [OK]
Hint: Raise error if score is less than 0 or greater than 100 [OK]