Playing with exceptions

I’ve just been having a little play with exceptions, as a new colleague wanted to understand how different errors could be handled. There is a good description of how they work in the “Exceptions, Catch, and Throw” chapter of the origin Pickaxe book.

I created the following script to demonstrate how it works

module Play
  def self.do &er
    begin
      puts "\n"
      er.call
    rescue SyntaxError, KeyError => e
      puts "One of SyntaxError, KeyError"
      output(e)
    rescue RuntimeError => e
      puts "Another known error"
      output(e)
    rescue => e
      puts 'Unknown error'
      output(e)
    end
  end

  def self.output(error)
    puts "#{error.class}: #{error.message}"
  end
end

Play.do {raise SyntaxError}

Play.do {raise "Gor Blimey"}

Play.do {HeBeJeeBees}
This entry was posted in Ruby. Bookmark the permalink.