Bird
0
0

You want to create a custom exception that stores an error code and a message. Which is the best practice to implement it?

hard📝 Application Q15 of 15
Python - Custom Exceptions
You want to create a custom exception that stores an error code and a message. Which is the best practice to implement it?
Aclass ErrorCodeException(Exception): def __init__(self, code, message): self.code = code self.message = message
Bclass ErrorCodeException: def __init__(self, code, message): self.code = code self.message = message
Cclass ErrorCodeException(Exception): def __init__(self, code, message): super().__init__(message) self.code = code
Dclass ErrorCodeException(Exception): pass
Step-by-Step Solution
Solution:
  1. Step 1: Check inheritance and initialization

    class ErrorCodeException(Exception): def __init__(self, code, message): super().__init__(message) self.code = code inherits Exception and calls super().__init__(message) to set the message properly.
  2. Step 2: Compare with other options

    class ErrorCodeException(Exception): def __init__(self, code, message): self.code = code self.message = message does not call super().__init__, so message may not behave like a normal exception message. class ErrorCodeException: def __init__(self, code, message): self.code = code self.message = message lacks inheritance. class ErrorCodeException(Exception): pass has no code or message storage.
  3. Final Answer:

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

    Inherit Exception and call super() with message = B [OK]
Quick Trick: Call super().__init__(message) to set exception message [OK]
Common Mistakes:
  • Not calling super().__init__ for message
  • Not inheriting from Exception
  • Storing message without Exception support

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Python Quizzes