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:
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.
Step 2: Verify initialize method
It calls super(msg) to set the message and stores code in @code correctly.
Final Answer:
class CodeError < StandardError with attr_reader and initialize(msg, code) -> Option C
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
Master "Error Handling" in Ruby
9 interactive learning modes - each teaches the same concept differently