Bird
0
0

What will be printed when the following code is executed?

medium📝 Predict Output Q4 of 15
Python - Custom Exceptions
What will be printed when the following code is executed?
class CustomError(Exception):
    def __init__(self, message):
        self.message = message

try:
    raise CustomError('Error occurred')
except CustomError as e:
    print(e.message)
ATraceback error
BCustomError object
CNone
DError occurred
Step-by-Step Solution
Solution:
  1. Step 1: Understand the class definition

    The CustomError class stores the message in an instance variable self.message.
  2. Step 2: Raising the exception

    The exception is raised with the message 'Error occurred'.
  3. Step 3: Catching and printing

    In the except block, e.message accesses the stored message and prints it.
  4. Final Answer:

    Error occurred -> Option D
  5. Quick Check:

    Accessing exception attributes directly prints stored message [OK]
Quick Trick: Access exception attributes to get custom messages [OK]
Common Mistakes:
  • Printing the exception object directly without __str__ method
  • Assuming print(e) prints the message without overriding __str__
  • Not storing the message in an instance variable

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Python Quizzes