Read more

Do not rescue inline in Ruby

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 online protection

Rails Long Term Support

Rails LTS provides security patches for old versions of Ruby on Rails (2.3, 3.2, 4.2 and 5.2)

  • Prevents you from data breaches and liability risks
  • Upgrade at your own pace
  • Works with modern Rubies
Read more Show archive.org snapshot

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)