Ruby exceptions and rescue blocks

A common syntax pattern in Ruby is catching exceptions like this:

begin
  do_stuff
rescue
  do_other_stuff
end

Inside the rescue block you’ll have the exception object available in the predefined global variable $!. An important thing to know is that this way you’ll catch only StandardError (and derived) exceptions. Most ruby exceptions actually derive from this class, but some do not. If you want a true catch-all exception block you have to do like this:

begin
  do_stuff
rescue Exception
  do_other_stuff
end

Try it yourself:

begin
  raise "Hi, I'm an exception"
rescue
  puts $!.class
end

This will show a RunTimeError, caught by the simple rescue statement.

begin
  eval(";!@")
rescue 
  puts $!.class
end

This will give an uncaught SyntaxError

begin
  eval(";!@")
rescue Exception
  puts $!.class
end

This will catch it.