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?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Try and rescue serve different purposes. The purpose of
tryis to save you from having to do:Or any situation where the parent object can possibly be nil, which would cause a NoMethodError on NilClass. The purpose of
rescueis to handle exceptions that get thrown by your method invocation. If you expect an exception from callinguser.email, then you canrescue nilit to prevent the exception from bubbling up.In general, I’d say avoid using
rescue nilunless you know explicitly what exceptions you are rescuing because you could be rescuing a different exception, and you would never know it becauserescue nilwould prevent you from seeing it. At the very least maybe you could log it: