Exception handling

begin...rescue...ensure...end

A begin...end block can offset a section of code. It is typically used for exception handling.

begin
  puts "a bare begin/end alone isn't terribly useful'
end
begin
  puts "however when used with a rescue, exception handling results"
  raise Exception.new("my exception")
rescue Exception => e
  puts e.backtrace
end

A begin...end block can stand alone, with one or more rescue blocks, and/or with an ensure block.

begin
  puts "ensure blocks are useful for cleaning up resources regardless of errors that may occur"
  f = File.open("myfile")
  raise Exception.new
rescue NameError => n
  # no NameError raised, so we'll not get here
ensure
  # but we'll always get here, unless the interpreter or thread terminates
  f.close
end

Note that Ruby's standard scoping for local variables holds for begin...end blocks as well: there is only one scope in a given method (not counting block-scoped variables).

The anonymous form of rescue only catches exceptions that descend from StandardError, as follows:

begin
  eval "\"" # raises a SyntaxError
rescue => e
  # The SyntaxError will not be caught
end

Compare to:

begin
  raise NameError.new("Some name error")
rescue => e
  # The NameError will be caught
end