0
0
Pythonprogramming~10 mins

Why custom exceptions are needed in Python - Test Your Understanding

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

Complete the code to raise a built-in exception when a number is negative.

Python
if number < 0:
    raise [1]("Negative number not allowed")
Drag options to blanks, or click blank then click option'
AValueError
BCustomError
CException
DTypeError
Attempts:
3 left
💡 Hint
Common Mistakes
Using a custom exception when a built-in one fits.
Using TypeError which is for wrong data types.
2fill in blank
medium

Complete the code to define a custom exception named MyError.

Python
class [1](Exception):
    pass
Drag options to blanks, or click blank then click option'
AError
BMyError
CCustomException
DException
Attempts:
3 left
💡 Hint
Common Mistakes
Using Exception as the class name.
Not inheriting from Exception.
3fill in blank
hard

Fix the error in raising the custom exception with a message.

Python
raise [1]("This is a custom error message")
Drag options to blanks, or click blank then click option'
AError
BCustomError
CMyError
DException
Attempts:
3 left
💡 Hint
Common Mistakes
Using a generic Exception instead of the custom one.
Using a wrong class name.
4fill in blank
hard

Fill both blanks to create a dictionary comprehension that includes only keys with values greater than 10.

Python
filtered = {k: v for k, v in data.items() if v [1] 10 and isinstance(v, [2])}
Drag options to blanks, or click blank then click option'
A>
Bint
C<
Dstr
Attempts:
3 left
💡 Hint
Common Mistakes
Using '<' instead of '>' for comparison.
Checking for str instead of int.
5fill in blank
hard

Fill all three blanks to create a custom exception class with a message attribute and raise it.

Python
class [1](Exception):
    def __init__(self, message):
        self.[2] = message
        super().__init__(message)

raise [3]("Custom error occurred")
Drag options to blanks, or click blank then click option'
ACustomError
Bmsg
Dmessage
Attempts:
3 left
💡 Hint
Common Mistakes
Using different names for class and raise.
Using 'msg' instead of 'message' attribute.