Catching exceptions in Ruby

Here’s how:

begin

  code_that_raises_an_exception…

  print “should not get here”

rescue

  print “Exception…”

end

To log it you could use:

rescue Exception => exception

  logger.error(“Exception details: #{exception}”)

Note, to catch specific exceptions, retry code on exceptions see: 

http://www.ruby-doc.org/docs/ProgrammingRuby/html/tut_exceptions.html

A more light weight guide with a good list of the Ruby Exception hierarchy is here:

http://www.skorks.com/2009/09/ruby-exceptions-and-exception-handling/

Also see:

http://stackoverflow.com/questions/766147/automatically-logging-exceptions-in-ruby

Leave a Reply

Your email address will not be published. Required fields are marked *