Bird
0
0

You want to create a custom exception ValidationError that stores an error code along with the message. Which code correctly implements this?

hard📝 Application Q15 of 15
Python - Custom Exceptions
You want to create a custom exception ValidationError that stores an error code along with the message. Which code correctly implements this?
Aclass ValidationError(Exception): def __init__(self, message): self.code = 0 super().__init__(message)
Bclass ValidationError(Exception): def __init__(self, message, code): self.message = message self.code = code
Cclass ValidationError(Exception): def __init__(self, code): super().__init__(code)
Dclass ValidationError(Exception): def __init__(self, message, code): super().__init__(message) self.code = code
Step-by-Step Solution
Solution:
  1. Step 1: Understand how to extend Exception with extra attributes

    To add an error code, override __init__ and call super().__init__(message) to set the message properly.
  2. Step 2: Check which option correctly calls super().__init__ and stores code

    class ValidationError(Exception): def __init__(self, message, code): super().__init__(message) self.code = code calls super().__init__(message) and assigns self.code = code, correctly storing both.
  3. Final Answer:

    class ValidationError(Exception): def __init__(self, message, code): super().__init__(message) self.code = code -> Option D
  4. Quick Check:

    Call super().__init__(message) and store extra attributes [OK]
Quick Trick: Call super().__init__(message) to set message, then add code [OK]
Common Mistakes:
  • Not calling super().__init__ for message
  • Assigning message without super call
  • Missing code attribute assignment

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Python Quizzes