`var = something rescue nil` behavior

In Ruby, you can write rescue at the end of the job to catch any errors that may occur. I have a function (below: a_function_that_may_fail ) where it is convenient to give it an error if certain conditions are not met. The following code works well

 post = {} # Other Hash stuff post['Caption'] = a_function_that_may_fail rescue nil 

However, I would like the message ['Caption'] not even set if the function does not work.

I know that I can:

 begin post['Caption'] = a_function_that_may_fail rescue end 

but this seems a bit overwhelming - is there a simpler solution?

+7
ruby exception-handling
source share
3 answers

The problem is priority. The simplest solution:

 (post['Caption'] = a_function_that_may_fail) rescue nil 

A change of priority like this is a little esoteric. It would probably be better if you could rewrite your a_function_that_may_fail to return nil if it doesn't work.

You can also use a temporary variable and check the nilness value:

 caption = a_function_that_may_fail rescue nil post['Caption'] = caption unless caption.nil? 

In fact, the slight difference is that it does not set post['Caption'] if a_function_that_may_fail did not raise an exception but returned nil .

+19
source share
 post.store('Caption', a_function_that_may_fail) rescue nil 
+3
source share

make sure your method returns either nil or false :

 def this_may_fail some_logic rescue nil end 

you can use the if modifier to check the return value of your method and assign a value only if it is not nil or false :

 post['Caption'] = this_may_fail if this_may_fail 

or you can cache the return value of this_may_fail in a local variable if you don't like calling the method twice for the if condition and assignment.

 the_value = this_may_fail post['Caption'] = the_value if the_value 

also notices that the rescue modifier only catches StandardError and its subclasses.

+2
source share

All Articles