0
0
Pythonprogramming~10 mins

Creating exception classes in Python - Interactive Practice

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

Complete the code to define a new exception class named MyError that inherits from Exception.

Python
class MyError([1]):
    pass
Drag options to blanks, or click blank then click option'
ABaseException
BException
CError
Dobject
Attempts:
3 left
💡 Hint
Common Mistakes
Inheriting from 'object' instead of 'Exception'.
Using 'Error' which is not a built-in base class.
2fill in blank
medium

Complete the code to raise the custom exception MyError with the message 'Oops!'.

Python
raise [1]('Oops!')
Drag options to blanks, or click blank then click option'
AMyError
BException
CError
DBaseException
Attempts:
3 left
💡 Hint
Common Mistakes
Raising the base Exception instead of the custom one.
Using a class name that was not defined.
3fill in blank
hard

Fix the error in the code to correctly define a custom exception MyError that inherits from Exception.

Python
class MyError(Exception):
    def __init__(self, message):
        super().[1](message)
Drag options to blanks, or click blank then click option'
A__init__
Binit
Cconstructor
Dsuper_init
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'init' without underscores.
Using a made-up method name like 'constructor'.
4fill in blank
hard

Fill both blanks to define a custom exception MyError that stores a message and returns it when converted to string.

Python
class MyError(Exception):
    def __init__(self, [1]):
        self.[2] = [1]
Drag options to blanks, or click blank then click option'
Amessage
Bmsg
Cerror
Dtext
Attempts:
3 left
💡 Hint
Common Mistakes
Using different names for parameter and attribute causing errors.
Using undefined variable names.
5fill in blank
hard

Fill both blanks to complete the __str__ method that returns the error message of MyError.

Python
class MyError(Exception):
    def __init__(self, message):
        self.message = message
    def __str__(self):
        return [1].[2]
Drag options to blanks, or click blank then click option'
Aself
Bmessage
Cmsg
Dtext
Attempts:
3 left
💡 Hint
Common Mistakes
Returning undefined variables.
Not using 'self' to access attributes.