Bird
0
0

Examine this code snippet:

medium📝 Debug Q7 of 15
Python - Custom Exceptions
Examine this code snippet:
class CustomError(Exception):
    def __init__(self, msg):
        self.msg = msg

try:
    raise CustomError('Error occurred')
except CustomError as e:
    print(e)

What issue will arise when running this code?
AThe exception prints an empty message because __str__ is not defined
BThe code raises a syntax error due to incorrect exception raising
CThe exception is not caught because the except block is wrong
DThere is no issue; the code runs and prints the error message
Step-by-Step Solution
Solution:
  1. Step 1: Analyze exception class

    The class stores the message in self.msg but does not override __str__.
  2. Step 2: Effect on printing exception

    Printing the exception calls __str__, which defaults to the base Exception's method, resulting in an empty message.
  3. Final Answer:

    The exception prints an empty message because __str__ is not defined -> Option A
  4. Quick Check:

    Override __str__ to display custom messages [OK]
Quick Trick: Override __str__ to show exception messages [OK]
Common Mistakes:
  • Assuming message prints automatically
  • Confusing syntax errors with runtime behavior
  • Believing except block is incorrect

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Python Quizzes