Ruby exception-handling quiz

Test your knowledge of Ruby's rescue/else/ensure exception handling construct! Fire up irb to check your answers.

1) What is the value of x?

x = begin 1; rescue 2; else 3;  ensure 4; end

2. What does this method return?

def test
  return 1
rescue
  return 2
else
  return 3
end

3. What does this method return?

def test
  return 1
ensure
  return 2
end

4. How about this one?

def test
  1
ensure
  2
end

5. What kind of exception does this method raise?

def test
  raise ArgumentError
rescue ArgumentError
  raise TypeError
end

6. What kind of exception does this method raise?

def test
  raise ArgumentError
ensure
  raise TypeError
end

7. What does this method do?

def test
  3.times do |x|
    begin
      puts x
      raise "error"
    ensure
      next
    end
  end
end

Books

Comprehensive coverage of Ruby 1.8 and 1.9

"The New Most Important Ruby Book"
Peter Cooper,
rubyinside.com

Completely updated for Ajax and Web 2.0

"A must-have reference"
Brendan Eich,
creator of JavaScript

The classic Java quick-reference

Advertising

Pages

Hosted By

Powered by Movable Type 4.21-en