0
0
Rubyprogramming~10 mins

Custom exception classes in Ruby - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to define a custom exception class named MyError.

Ruby
class MyError < [1]
end
Drag options to blanks, or click blank then click option'
AException
BStandardError
CRuntimeError
DError
Attempts:
3 left
💡 Hint
Common Mistakes
Inheriting directly from Exception can cause unexpected behavior.
Using a non-existent class like Error will cause a NameError.
2fill in blank
medium

Complete the code to raise the custom exception MyError with a message.

Ruby
raise [1], "Something went wrong"
Drag options to blanks, or click blank then click option'
AMyError
BMyError.new
CStandardError
DException
Attempts:
3 left
💡 Hint
Common Mistakes
Using MyError.new raises an instance but is not the common pattern.
Raising Exception or StandardError raises built-in errors, not the custom one.
3fill in blank
hard

Fix the error in the code to rescue the custom exception MyError.

Ruby
begin
  # some code
rescue [1] => e
  puts e.message
end
Drag options to blanks, or click blank then click option'
ARuntimeError
BStandardError
CException
DMyError
Attempts:
3 left
💡 Hint
Common Mistakes
Rescuing Exception or StandardError catches too many errors.
Using RuntimeError does not catch MyError unless it inherits from it.
4fill in blank
hard

Fill both blanks to define a custom exception with a message method.

Ruby
class MyError < [1]
  def [2]
    "Custom error occurred"
  end
end
Drag options to blanks, or click blank then click option'
AStandardError
Bmessage
CException
Dinitialize
Attempts:
3 left
💡 Hint
Common Mistakes
Defining initialize instead of message changes how the error is created.
Inheriting from Exception is less common and can cause issues.
5fill in blank
hard

Fill all three blanks to raise and rescue a custom exception with a message.

Ruby
begin
  raise [1], "Oops!"
rescue [2] => e
  puts e.[3]
end
Drag options to blanks, or click blank then click option'
AMyError
Cmessage
DStandardError
Attempts:
3 left
💡 Hint
Common Mistakes
Raising and rescuing different exception classes causes errors.
Using e.to_s instead of e.message changes output format.