Bird
Raised Fist0
Pythonprogramming~20 mins

Custom error messages in Python - Practice Problems & Coding Challenges

Choose your learning style10 modes available

Start learning this pattern below

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
Challenge - 5 Problems
🎖️
Custom Error Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
What is the output of this code with a custom error message?
Look at the code below. What will it print when run?
Python
def check_age(age):
    if age < 18:
        raise ValueError("Age must be at least 18")
    return "Access granted"

try:
    print(check_age(16))
except ValueError as e:
    print(e)
AAge must be at least 18
BAccess granted
CValueError
DTypeError
Attempts:
2 left
💡 Hint
The function raises an error if age is less than 18, and the error message is printed.
Predict Output
intermediate
2:00remaining
What error message is shown here?
What will this code print when run?
Python
def divide(a, b):
    if b == 0:
        raise ZeroDivisionError("Cannot divide by zero!")
    return a / b

try:
    print(divide(10, 0))
except ZeroDivisionError as e:
    print(e)
ACannot divide by zero!
BNone
CZeroDivisionError
Ddivision by zero
Attempts:
2 left
💡 Hint
The custom message inside the error is printed by the except block.
Predict Output
advanced
2:00remaining
What is the output of this code with a custom exception class?
What will this code print when run?
Python
class MyError(Exception):
    def __init__(self, message):
        super().__init__(message)

try:
    raise MyError("Something went wrong!")
except MyError as e:
    print(f"Error: {e}")
AMyError
BError: Something went wrong!
CException
DSomething went wrong!
Attempts:
2 left
💡 Hint
The custom exception message is passed to the print statement with a prefix.
Predict Output
advanced
2:00remaining
What error message is shown here with multiple exceptions?
What will this code print when run?
Python
def check_value(x):
    if x < 0:
        raise ValueError("Negative value not allowed")
    elif x == 0:
        raise ZeroDivisionError("Zero is not allowed")
    return x

try:
    check_value(0)
except ValueError as e:
    print(e)
except ZeroDivisionError as e:
    print(e)
ANegative value not allowed
BZeroDivisionError
CValueError
DZero is not allowed
Attempts:
2 left
💡 Hint
The input is zero, so the ZeroDivisionError is raised and caught.
🧠 Conceptual
expert
3:00remaining
Which option correctly defines a custom exception with a default message?
Choose the code that defines a custom exception class with a default error message that can be overridden.
A
class CustomError(Exception):
    message = "Default error message"
    def __init__(self, message):
        self.message = message
B
class CustomError(Exception):
    def __init__(self):
        self.message = "Default error message"
    def __str__(self):
        return self.message
C
class CustomError(Exception):
    def __init__(self, message="Default error message"):
        super().__init__(message)
D
class CustomError(Exception):
    def __init__(self, message):
        print(message)
Attempts:
2 left
💡 Hint
The correct class passes the message to the base Exception class and allows a default.

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

  1. Step 1: Understand the raise statement

    The raise keyword is used to stop the program and throw an error.
  2. Step 2: Purpose of custom messages

    Adding a message like 'Custom message' helps explain why the error happened.
  3. Final Answer:

    To stop the program and show a specific error message when a condition is not met. -> Option B
  4. 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

  1. Step 1: Identify the correct keyword

    In Python, raise is used to throw errors, not throw or error.
  2. 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.
  3. Final Answer:

    raise ValueError('Invalid input') -> Option D
  4. Quick Check:

    raise + ErrorType('message') = correct syntax [OK]
Hint: Use raise ErrorType('message') to create custom errors [OK]
Common Mistakes:
  • Using throw instead of raise
  • Placing message before error type
  • Missing parentheses around the message
3. What will be the output of this code?
def check_age(age):
    if age < 18:
        raise ValueError('Age must be 18 or older')
    return 'Access granted'

print(check_age(16))
medium
A. Access granted
B. None
C. ValueError: Age must be 18 or older
D. SyntaxError

Solution

  1. Step 1: Check the condition in the function

    The function raises a ValueError if age is less than 18. Here, age is 16, so the error triggers.
  2. Step 2: Understand what happens on raise

    When the error is raised, the program stops and shows the error message instead of returning 'Access granted'.
  3. Final Answer:

    ValueError: Age must be 18 or older -> Option C
  4. Quick Check:

    raise triggers error output = ValueError message [OK]
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

  1. 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.
  2. Step 2: Correct way to raise errors

    Use raise ValueError('message') or another Exception class, not a plain string.
  3. Final Answer:

    You cannot raise a string directly; it must be an Exception type. -> Option A
  4. 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

  1. 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.
  2. 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.
  3. 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
  4. 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]
Common Mistakes:
  • Using and instead of or in condition
  • Raising error for valid scores instead of invalid
  • Checking only equality instead of range