Best Practice: Try vs Rescue

What is the practice? 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 them?

+61
ruby ruby-on-rails
May 19 '11 at 18:39
source share
3 answers

Trying and salvation serve different purposes. The goal of try is to save you the need:

 if user && user.email 

Or any situation where the parent can be zero, which raises a NoMethodError on a NilClass. The goal of rescue is to handle exceptions that are thrown by a method call. If you expect the exception to be thrown by user.email , you can rescue nil to prevent it, so that the exception does not happen.

In general, I would say avoid using rescue nil unless you know exactly which exceptions you are saving, because you can save another exception, and you will never know about it because rescue nil prevent you from seeing it. At least, maybe you can register it:

 begin ...some code... rescue => ex logger.error ex.message end 
+94
May 19 '11 at 18:49
source share

Both seem suspicious and may mask other errors. Are you sure you really want to get zero? Maybe it’s better to check if there are any comments in the first place, and explicitly cover the empty case?

+8
May 19 '11 at 18:46
source share

Nothing happened - a wonderful conversation by Sandy Mets, which helps to understand why @AdamByrtek is in place, and why should we all report failed cases in a more intelligent, more object-oriented way, which is x ? y : nil x ? y : nil

+4
Aug 12 '15 at 7:15
source share



All Articles