Chapter 12 - Exceptions

Exercise 3: Handling multiple exception types

The call to random_failure raises either a ThisError, ThatError, or TheOtherError, randomly. Rescue ThisError, and print the message “I caught this!”. Rescue ThatError, and print “I caught that!”. Allow TheOtherError to fail normally.

class ThisError < StandardError
end

class ThatError < StandardError
end

class TheOtherError < StandardError
end

def random_failure
  number = rand(0..2)
  if number == 0
    raise ThisError, "Whoops!"
  elsif number == 1
    raise ThatError, "Uh, oh!"
  elsif number == 2
    raise TheOtherError, "Oh, no!"
  end
end

begin
  random_failure
rescue ThisError
  puts "I caught this!"
rescue ThatError
  puts "I caught that!"
end

Try running your code repeatedly. You should see one of these three outputs each time:

I caught this!
I caught that!
test.rb:17:in `random_failure': Oh, no! (TheOtherError)
        from test.rb:22:in `<main>'