0
0
Pythonprogramming~10 mins

Custom error messages in Python - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to raise a ValueError with a custom message.

Python
if age < 0:
    raise ValueError([1])
Drag options to blanks, or click blank then click option'
A"Age cannot be negative"
BAge cannot be negative
CValueError
Dprint("Error")
Attempts:
3 left
💡 Hint
Common Mistakes
Forgetting quotes around the message
Using a variable name instead of a string
Trying to print instead of raise
2fill in blank
medium

Complete the code to raise a TypeError with a custom message when input is not a string.

Python
if not isinstance(name, str):
    raise TypeError([1])
Drag options to blanks, or click blank then click option'
AInput must be a string
BTypeError
C"Input must be a string"
Dprint("Wrong type")
Attempts:
3 left
💡 Hint
Common Mistakes
Not using quotes for the message
Raising the wrong error type
Using print instead of raise
3fill in blank
hard

Fix the error in raising a custom error message for zero division.

Python
if denominator == 0:
    raise ZeroDivisionError([1])
Drag options to blanks, or click blank then click option'
Aprint("Error")
BZeroDivisionError
C0
D"Cannot divide by zero"
Attempts:
3 left
💡 Hint
Common Mistakes
Passing the error class instead of a message
Using print instead of raise
Passing a number instead of a string
4fill in blank
hard

Fill both blanks to raise a custom error with a message including the invalid value.

Python
if score < 0 or score > 100:
    raise ValueError(f"Invalid score: [1]")

# Use the variable name in the message
invalid_value = [2]
Drag options to blanks, or click blank then click option'
Ascore
Bvalue
Dscore_value
Attempts:
3 left
💡 Hint
Common Mistakes
Using a wrong variable name
Not using the variable inside the f-string
Assigning invalid_value to a non-existent variable
5fill in blank
hard

Fill all three blanks to raise a custom error with a message showing the invalid input and its type.

Python
if not isinstance(data, dict):
    raise TypeError(f"Expected dict but got [1] of type [2]")

actual_type = type([3]).__name__
Drag options to blanks, or click blank then click option'
Adata
Dinput
Attempts:
3 left
💡 Hint
Common Mistakes
Using different variable names in blanks
Not using f-string formatting
Forgetting to get the type name with __name__