Implicit exception handling

Ruby does a fantastic job of making code look good, and today's tip is no exception, pun intended. Take this code, for example:

def delete_items(ids)
  begin
    # This could fail if any of the IDs were not found
    items = find(ids)
    items.each do |i|
      i.parent.log("Deleted #{item.name}")
      i.destroy
    end
  rescue
    return false
  end

  return true
end

While a simple example, it gets the point across. But the begin/rescue control loop has a few tricks up its sleeve, namely else and ensure. Adding an else into exception handling code will do just what you would expect: get run in case no exception was thrown. The other term, ensure denotes a block of code that will be run regardless of whether an exception was thrown or not. What we want to focus on here is the else clause, because Ruby has an implicit begin at the beginning of a method, which cleans up our code a tiny bit–but enough to make it worth doing, in my opinion:

def delete_items(ids)
  # This could fail if any of the IDs were not found
  items = find(ids)
  items.each do |i|
    i.parent.log("Deleted #{item.name}")
    i.destroy
  end
rescue
  return false
else
  return true
end

Looking good, Billy Ray.

Leave a Reply