Bird
0
0

You want to raise a custom error type ArgumentError with a message "Invalid input" when a method receives a negative number. Which code correctly does this?

hard📝 Application Q15 of 15
Ruby - Error Handling
You want to raise a custom error type ArgumentError with a message "Invalid input" when a method receives a negative number. Which code correctly does this?
AArgumentError.raise("Invalid input") if number < 0
Braise ArgumentError, "Invalid input" if number < 0
Craise "ArgumentError: Invalid input" if number < 0
Draise ArgumentError("Invalid input") if number < 0
Step-by-Step Solution
Solution:
  1. Step 1: Understand how to raise custom error types

    In Ruby, you can raise a specific error class by passing it as the first argument to raise, followed by the message.
  2. Step 2: Check each option's syntax

    raise ArgumentError, "Invalid input" if number < 0 correctly uses raise ArgumentError, "Invalid input". raise "ArgumentError: Invalid input" if number < 0 treats the error as a string only. ArgumentError.raise("Invalid input") if number < 0 is invalid as raise is not a method on ArgumentError. raise ArgumentError("Invalid input") if number < 0 is invalid syntax.
  3. Final Answer:

    raise ArgumentError, "Invalid input" if number < 0 -> Option B
  4. Quick Check:

    Raise with error class and message = C [OK]
Quick Trick: Use raise ErrorClass, "message" for custom errors [OK]
Common Mistakes:
  • Passing error as string only
  • Using wrong syntax with parentheses
  • Confusing new method call with raise

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes