Ruby exceptions and rescue blocks
A common syntax pattern in Ruby is catching exceptions like this:
begin
do_stuff
rescue
do_other_stuff
endInside 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
endTry it yourself:
begin
raise "Hi, I'm an exception"
rescue
puts $!.class
endThis will show a RunTimeError, caught by the simple rescue statement.
begin
eval(";!@")
rescue
puts $!.class
endThis will give an uncaught SyntaxError
begin
eval(";!@")
rescue Exception
puts $!.class
endThis will catch it.