Bird
0
0

You want to create a custom exception InvalidAgeError that triggers when age is less than 18. Which code correctly raises this exception inside a method check_age?

hard📝 Application Q8 of 15
Ruby - Error Handling
You want to create a custom exception InvalidAgeError that triggers when age is less than 18. Which code correctly raises this exception inside a method check_age?
Aclass InvalidAgeError < StandardError; end def check_age(age) raise InvalidAgeError, "Age must be 18 or older" if age < 18 end
Bclass InvalidAgeError < Exception; end def check_age(age) raise "InvalidAgeError" if age < 18 end
Cdef check_age(age) if age < 18 throw InvalidAgeError end end
Dclass InvalidAgeError end def check_age(age) raise InvalidAgeError.new("Too young") if age < 18 end
Step-by-Step Solution
Solution:
  1. Step 1: Check correct class definition and inheritance

    class InvalidAgeError < StandardError; end def check_age(age) raise InvalidAgeError, "Age must be 18 or older" if age < 18 end defines InvalidAgeError inheriting from StandardError, which is correct.
  2. Step 2: Check raise usage inside method

    class InvalidAgeError < StandardError; end def check_age(age) raise InvalidAgeError, "Age must be 18 or older" if age < 18 end raises InvalidAgeError with message if age < 18, which matches requirement.
  3. Final Answer:

    Option A code correctly raises InvalidAgeError when age < 18 -> Option A
  4. Quick Check:

    Define custom error and raise with message [OK]
Quick Trick: Raise custom error with message inside method [OK]
Common Mistakes:
  • Using throw instead of raise
  • Raising string instead of exception
  • Not inheriting from StandardError

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes