Read more

Do not rescue inline in Ruby

Avatar
Arne Hartherz
February 29, 2012Software engineer at makandra GmbH

When you are calling a method that may raise an exception that you don't care about, you might think of doing something like this:

@user = User.power_find(something) rescue User.new
Illustration web development

Do you need DevOps-experts?

Your development team has a full backlog? No time for infrastructure architecture? Our DevOps team is ready to support you!

  • We build reliable cloud solutions with Infrastructure as code
  • We are experts in security, Linux and databases
  • We support your dev team to perform
Read more

Do not do that! You will be rescuing away StandardError and all its subclasses, like NameError -- meaning that even a typo in your code won't raise an error.

Instead, rescue the exception type that you are expecting:

@user = begin
  User.power_find(something)
rescue ActiveRecord::RecordNotFound
  User.new
end

This also applies to the quite popular "rescue nil" and "full" rescue blocks that don't explicitly rescue away an error class:

begin
  # do stuff
rescue
  # rescues any StandardError
end

Note that there may be cases where you want to rescue all errors. Only use that if you know the impact it has on your application and are absolutely fine with it.

Posted by Arne Hartherz to makandra dev (2012-02-29 14:36)