Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best Practice: Try vs Rescue

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?

like image 851
LuisVM Avatar asked May 19 '11 18:05

LuisVM


People also ask

Can we use rescue without begin?

The method definition itself does the work of begin , so you can omit it. You can also do this with blocks. Now, there is one more way to use the rescue keyword without begin .

What happens if in a begin rescue block the rescue code has an error?

The code between “begin” and “rescue” is where a probable exception might occur. If an exception occurs, the rescue block will execute. You should try to be specific about what exception you're rescuing because it's considered a bad practice to capture all exceptions.

How do you handle exceptions in Rails?

Exception handling in Ruby on Rails is similar to exception handling in Ruby. Which means, we enclose the code that could raise an exception in a begin/end block and use rescue clauses to tell Ruby the types of exceptions we want to handle.

Does Ruby have try catch?

In Ruby we have a way to deal with these cases, we have begin, end(default try catch) and we can use try and catch, both try catch and raise rescue used for the same purpose, one will throw exception(throw or raise) with any specific name inside another(catch or rescue).


1 Answers

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 
like image 130
Jack Chu Avatar answered Sep 23 '22 21:09

Jack Chu