Bird
0
0

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

hard📝 Application Q15 of 15
Ruby - Error Handling
You want to create a custom exception that stores an error code along with the message. Which code correctly implements this?
Aclass CodeError < StandardError def initialize(msg) @code = msg end end
Bclass CodeError def initialize(msg, code) @code = code super(msg) end end
Cclass CodeError < StandardError attr_reader :code def initialize(msg, code) super(msg) @code = code end end
Dclass CodeError < Exception def initialize(code) @code = code end end
Step-by-Step Solution
Solution:
  1. Step 1: Check inheritance and attribute

    class CodeError < StandardError attr_reader :code def initialize(msg, code) super(msg) @code = code end end inherits from StandardError and defines attr_reader for code to access it.
  2. Step 2: Verify initialize method

    It calls super(msg) to set the message and stores code in @code correctly.
  3. Final Answer:

    class CodeError < StandardError with attr_reader and initialize(msg, code) -> Option C
  4. Quick Check:

    Custom exception with extra data = class CodeError < StandardError attr_reader :code def initialize(msg, code) super(msg) @code = code end end [OK]
Quick Trick: Use attr_reader and call super(msg) in initialize [OK]
Common Mistakes:
  • Not inheriting from StandardError
  • Calling super after instance variables
  • Missing attr_reader for code

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes