Ruby: Do not rescue without specifying exception classes

Updated . Posted . Visible to the public. Repeats.

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

@user = User.something(123) rescue User.new # DON'T

or

@user = begin
  User.something(123)
rescue # DON'T
  User.new
end

This is bad. Do not do that.

You will be rescuing StandardError and all its subclasses, like NameError -- meaning that e.g. a typo in your code won't raise an error any more.

If you expect an error to be raised, you can always rescue for its class. Do that instead.

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

Any unexpected errors will then still be raising an exception that e.g. your application monitoring can pick up and notify you so you can fix it.

Note

StandardError does not include all error classes.
So, while it might seem that rescue without specifying exception classes might catch all possible errors, it actually does not.

If you ever really need to rescue all errors, you could rescue Exception.
Only do that if you know the impact it has on your application and are absolutely fine with it.

Profile picture of Arne Hartherz
Arne Hartherz
Last edit
Arne Hartherz
Keywords
inline, capture, catch
License
Source code in this card is licensed under the MIT License.
Posted by Arne Hartherz to makandra dev (2012-02-29 13:36)