Bird
Raised Fist0

You need a custom exception ValidationError that stores both an error message and an error code. Which implementation is best?

hard🚀 Application Q8 of Q15
Python - Custom Exceptions
You need a custom exception ValidationError that stores both an error message and an error code. Which implementation is best?
Aclass ValidationError(Exception): def __init__(self, message, code): self.message = message self.code = code
Bclass ValidationError(Exception): def __init__(self, message, code): super().__init__(message) self.code = code
Cclass ValidationError: def __init__(self, message, code): self.message = message self.code = code
Ddef ValidationError(message, code): self.message = message self.code = code
Step-by-Step Solution
Solution:
  1. Step 1: Inherit from Exception

    Custom exceptions must inherit from Exception for proper behavior.
  2. Step 2: Initialize base Exception

    Calling super().__init__(message) ensures the message is handled correctly by the base class.
  3. Step 3: Store additional attributes

    Assigning self.code stores the error code for later use.
  4. Final Answer:

    class ValidationError(Exception): def __init__(self, message, code): super().__init__(message) self.code = code correctly implements all requirements.
  5. Quick Check:

    Use super() to initialize Exception with message [OK]
Quick Trick: Call super().__init__ to set message in custom exceptions [OK]
Common Mistakes:
MISTAKES
  • Not inheriting from Exception
  • Not calling super().__init__
  • Defining exception as a function

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Python Quizzes