Bird
Raised Fist0

You want a custom exception ApiError that stores an error code and message, and returns a string like 'Error 404: Not Found' when printed. Which implementation is best?

hard🚀 Application Q8 of Q15
Python - Custom Exceptions
You want a custom exception ApiError that stores an error code and message, and returns a string like 'Error 404: Not Found' when printed. Which implementation is best?
Aclass ApiError(Exception): def __init__(self, code, message): super().__init__(message) self.code = code def __str__(self): return f'Error {self.code}: {self.args[0]}'
Bclass ApiError(Exception): def __init__(self, code, message): self.code = code self.message = message def __str__(self): return f'Error {self.code}: {self.message}'
Cclass ApiError(Exception): def __init__(self, code, message): self.code = code self.message = message
Dclass ApiError(Exception): def __str__(self): return 'Error occurred'
Step-by-Step Solution
Solution:
  1. Step 1: Initialize base Exception properly

    Call super().__init__(message) to set the message in the base class.
  2. Step 2: Store error code

    Assign self.code = code to keep the error code.
  3. Step 3: Customize string output

    Override __str__ to return the formatted string using self.code and self.args[0] (the message).
  4. Step 4: Why use self.args[0]?

    The base Exception stores the message in args, so using self.args[0] ensures consistency.
  5. Final Answer:

    class ApiError(Exception): def __init__(self, code, message): super().__init__(message) self.code = code def __str__(self): return f'Error {self.code}: {self.args[0]}' correctly implements all requirements.
  6. Quick Check:

    Call super().__init__ and override __str__ for custom message [OK]
Quick Trick: Use super().__init__ and override __str__ for custom exceptions [OK]
Common Mistakes:
MISTAKES
  • Not calling super().__init__ leading to missing message
  • Storing message only in self.message without base init
  • Not overriding __str__ to customize output

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Python Quizzes