Chapter 12 - Exceptions

Exercise 1: Rescuing Exceptions

The call to trip_over_curb raises an exception. Instead of allowing execution to halt, rescue the exception, and print the string "Caught you!".

def trip_over_curb
  raise "WHOA!"
end

trip_over_curb

Here’s the program output right now:

test.rb:2:in `trip_over_curb': WHOA! (RuntimeError)
        from test.rb:5:in `<main>'

When you’re ready, have a look at the solution.

Exercise 2: Handling the exception object

The call to send_sos raises an exception with a message containing some coordinates. Rescue the exception, and print “Sending rescue party to” followed by the coordinates in the exception message.

def send_sos
  raise "Latitude -50.75, Longitude 166.04"
end

send_sos

Here’s the output:

test.rb:2:in `send_sos': Latitude -50.75, Longitude 166.04 (RuntimeError)
        from test.rb:5:in `<main>'

When you’re ready, have a look at the solution.

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

random_failure

When you run your code repeatedly, you should see one of these three outputs:

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

When you’re ready, have a look at the solution.