Challenge - 5 Problems
Custom Exception Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of a custom exception message
What is the output of this Ruby code that defines and raises a custom exception?
Ruby
class MyError < StandardError def message "Custom error occurred" end end begin raise MyError rescue MyError => e puts e.message end
Attempts:
2 left
💡 Hint
Look at the message method inside the custom exception class.
✗ Incorrect
The custom exception class overrides the message method to return 'Custom error occurred'. When raised and rescued, printing e.message outputs this string.
❓ Predict Output
intermediate2:00remaining
Exception class inheritance check
What will this Ruby code output when checking the inheritance of a custom exception?
Ruby
class MyCustomError < RuntimeError; end puts MyCustomError < StandardError puts MyCustomError < RuntimeError puts MyCustomError < Exception
Attempts:
2 left
💡 Hint
Remember that RuntimeError inherits from StandardError, which inherits from Exception.
✗ Incorrect
MyCustomError inherits from RuntimeError, which inherits from StandardError, which inherits from Exception. So all comparisons return true.
🔧 Debug
advanced2:00remaining
Identify the error in custom exception raising
What error does this Ruby code raise when executed?
Ruby
class CustomError < StandardError; end def test raise CustomError, 123 rescue CustomError => e puts e.message end test
Attempts:
2 left
💡 Hint
Check how Ruby converts the second argument of raise to a message string.
✗ Incorrect
Ruby converts the second argument (123) to a string '123' for the exception message. So e.message outputs '123' without error.
❓ Predict Output
advanced2:00remaining
Custom exception with additional data
What is the output of this Ruby code that adds extra data to a custom exception?
Ruby
class DataError < StandardError attr_reader :code def initialize(msg, code) super(msg) @code = code end end begin raise DataError.new("Error happened", 404) rescue DataError => e puts "Message: #{e.message}, Code: #{e.code}" end
Attempts:
2 left
💡 Hint
Look at how the initialize method sets the message and code attributes.
✗ Incorrect
The initialize method calls super with the message and sets @code. The rescue block prints both correctly.
🧠 Conceptual
expert2:00remaining
Behavior of rescue with multiple custom exceptions
Given these custom exceptions, which rescue clause will catch the raised exception?
Ruby
class ErrorA < StandardError; end class ErrorB < ErrorA; end begin raise ErrorB rescue ErrorA puts "Caught ErrorA" rescue StandardError puts "Caught StandardError" end
Attempts:
2 left
💡 Hint
Remember that rescue catches exceptions of the specified class or its subclasses.
✗ Incorrect
ErrorB is a subclass of ErrorA, so the first rescue clause catches it and prints 'Caught ErrorA'.