0
0
Pythonprogramming~10 mins

Best practices for custom exceptions 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 define a custom exception class named MyError.

Python
class MyError([1]):
    pass
Drag options to blanks, or click blank then click option'
ACustomError
BError
CBaseException
DException
Attempts:
3 left
💡 Hint
Common Mistakes
Inheriting from BaseException causes catching issues.
Using a non-existent base class.
2fill in blank
medium

Complete the code to raise the custom exception MyError with a message.

Python
raise MyError([1])
Drag options to blanks, or click blank then click option'
AMyError
BError
C"An error occurred"
DException
Attempts:
3 left
💡 Hint
Common Mistakes
Passing the exception class instead of a message.
Not passing any argument.
3fill in blank
hard

Fix the error in the custom exception class to properly initialize the message.

Python
class MyError(Exception):
    def __init__(self, message):
        [1]
Drag options to blanks, or click blank then click option'
Asuper().__init__(message)
Bself.message = message
CException.__init__(self)
Dself.msg = message
Attempts:
3 left
💡 Hint
Common Mistakes
Only setting an attribute without calling the base constructor.
Calling base constructor without message.
4fill in blank
hard

Fill both blanks to create a custom exception with a code attribute and proper initialization.

Python
class MyError(Exception):
    def __init__(self, message, code):
        [1]
        [2] = code
Drag options to blanks, or click blank then click option'
Asuper().__init__(message)
Bself.message
Cself.code
DException.__init__(self, message)
Attempts:
3 left
💡 Hint
Common Mistakes
Not calling the base class __init__.
Assigning code to a wrong attribute name.
5fill in blank
hard

Fill all three blanks to catch the custom exception and print its message and code.

Python
try:
    raise MyError("Failed", 404)
except [1] as e:
    print(e[2])
    print(e[3])
Drag options to blanks, or click blank then click option'
AMyError
B.args[0]
C.code
DException
Attempts:
3 left
💡 Hint
Common Mistakes
Catching the wrong exception type.
Trying to print message directly without args.
Accessing a non-existent attribute.