Bird
0
0

Given this Ruby code, what will be printed?

hard📝 Application Q15 of 15
Ruby - Error Handling
Given this Ruby code, what will be printed?
def test
  begin
    raise ArgumentError, 'Wrong argument'
  rescue ZeroDivisionError
    puts 'Zero division error'
  rescue ArgumentError
    puts 'Argument error caught'
  ensure
    puts 'Always runs'
  end
end
test
AArgument error caught Always runs
BZero division error Always runs
CAlways runs Argument error caught
DNo output, error not handled
Step-by-Step Solution
Solution:
  1. Step 1: Identify raised error

    The code raises ArgumentError with message 'Wrong argument'.
  2. Step 2: Match rescue clauses

    The ArgumentError rescue clause runs and prints 'Argument error caught'.
  3. Step 3: Understand ensure block

    The ensure block always runs, printing 'Always runs'.
  4. Final Answer:

    Argument error caught Always runs -> Option A
  5. Quick Check:

    ArgumentError rescued, ensure always runs [OK]
Quick Trick: Ensure block runs after rescue regardless of error [OK]
Common Mistakes:
  • Thinking ensure runs before rescue
  • Assuming wrong rescue clause runs
  • Ignoring ensure block output

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes