Bird
0
0

What will be the output of this code?

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

try:
    raise MyError()
except MyError as e:
    print(e)
AMyError
BCustom error occurred
CException
DNo output
Step-by-Step Solution
Solution:
  1. Step 1: Understand __str__ method in custom exceptions

    The __str__ method defines the string shown when the exception instance is printed.
  2. Step 2: Check what print(e) outputs

    Since __str__ returns 'Custom error occurred', printing e outputs this string.
  3. Final Answer:

    Custom error occurred -> Option B
  4. Quick Check:

    Custom __str__ changes exception message output [OK]
Quick Trick: Override __str__ to customize exception message [OK]
Common Mistakes:
  • Ignoring __str__ method effect
  • Expecting default exception name output
  • Confusing __str__ with __repr__

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Python Quizzes