Bird
0
0

What will this code output?

medium📝 Predict Output Q4 of 15
Python - Custom Exceptions
What will this code output?
class Error(Exception):
    def __str__(self):
        return 'Custom error occurred'

try:
    raise Error()
except Error as e:
    print(e)
ATraceback with error message
BError
CNone
DCustom error occurred
Step-by-Step Solution
Solution:
  1. Step 1: Understand __str__ method

    The __str__ method defines the string representation of the exception instance.
  2. Step 2: Raising and catching the exception

    The exception Error is raised and caught in the except block as e.
  3. Step 3: Printing the exception instance

    Printing e calls e.__str__(), which returns 'Custom error occurred'.
  4. Final Answer:

    Custom error occurred -> Option D
  5. Quick Check:

    __str__ controls printed exception message [OK]
Quick Trick: Override __str__ to customize exception message [OK]
Common Mistakes:
  • Expecting default exception name to print
  • Not realizing __str__ changes print output
  • Confusing __repr__ with __str__

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Python Quizzes