Posted over 7 years ago. Visible to the public. Repeats.

Do not rescue inline in Ruby

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

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 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.

makandra has been working exclusively with Ruby on Rails since 2007. Our laser focus on a single technology has made us a leader in this space.

Owner of this card:

Arne Hartherz
Last edit:
over 2 years ago
by Henning Koch
About this deck:
We are makandra and do test-driven, agile Ruby on Rails software development.
License for source code
Posted by Arne Hartherz to makandra dev
This website uses cookies to improve usability and analyze traffic.
Accept or learn more