Best Practice: Try vs Rescue

Ruby on-RailsRuby

Ruby on-Rails Problem Overview


What is a best practice? To use try or use rescue?

user.try(:email)

VS

user.email rescue nil

post.try(:comments).try(:first).try(:author)

VS

post.comments.first.author rescue nil

Is there any difference in using any of these?

Ruby on-Rails Solutions


Solution 1 - Ruby on-Rails

Try and rescue serve different purposes. The purpose of try is to save you from having to do:

if user && user.email

Or any situation where the parent object can possibly be nil, which would cause a NoMethodError on NilClass. The purpose of rescue is to handle exceptions that get thrown by your method invocation. If you expect an exception from calling user.email, then you can rescue nil it to prevent the exception from bubbling up.

In general, I'd say avoid using rescue nil unless you know explicitly what exceptions you are rescuing because you could be rescuing a different exception, and you would never know it because rescue nil would prevent you from seeing it. At the very least maybe you could log it:

begin
  ...some code...
rescue => ex
  logger.error ex.message
end

Solution 2 - Ruby on-Rails

Both seem fishy and can mask other bugs. Are you sure you really want to get nil there? Maybe it would be better to check whether there are any comments first, and cover the empty case explicitly?

Solution 3 - Ruby on-Rails

Nothing is Something is an excellent talk by Sandi Metz that helps understand why @AdamByrtek is spot on, and why we should all be marking the failed cases in a smarter, more object-oriented way that x ? y : nil

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionLuisVMView Question on Stackoverflow
Solution 1 - Ruby on-RailsJack ChuView Answer on Stackoverflow
Solution 2 - Ruby on-RailsAdam ByrtekView Answer on Stackoverflow
Solution 3 - Ruby on-RailsJonathan_WView Answer on Stackoverflow