0
0
Rubyprogramming~20 mins

Custom exception classes in Ruby - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Custom Exception Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2: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
ACustom error occurred
BMyError
CStandardError
DRuntimeError
Attempts:
2 left
💡 Hint
Look at the message method inside the custom exception class.
Predict Output
intermediate
2: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
A
true
true
false
B
false
true
true
C
true
false
true
D
true
true
true
Attempts:
2 left
💡 Hint
Remember that RuntimeError inherits from StandardError, which inherits from Exception.
🔧 Debug
advanced
2: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
AArgumentError
BNoMethodError
COutputs '123'
DTypeError
Attempts:
2 left
💡 Hint
Check how Ruby converts the second argument of raise to a message string.
Predict Output
advanced
2: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
AMessage: Error happened, Code:
BMessage: Error happened, Code: 404
CMessage: , Code: 404
DRuntimeError
Attempts:
2 left
💡 Hint
Look at how the initialize method sets the message and code attributes.
🧠 Conceptual
expert
2: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
ACaught ErrorA
BNo output, exception not caught
CCaught StandardError
DRuntimeError
Attempts:
2 left
💡 Hint
Remember that rescue catches exceptions of the specified class or its subclasses.