tags:

views:

114

answers:

3

In ruby you can throw a rescue at the end of an assignment to catch any errors that might come up. I have a function (below: a_function_that_may_fail) where it's convenient to let it throw an error if certain conditions aren't met. The following code works well

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

However I'd like to have post['Caption'] not even set if the function fails.

I know I can do:

begin
  post['Caption'] = a_function_that_may_fail
rescue
end

but that feels a little excessive - is there a simpler solution?

A: 

make sure your method returns either nil or false:

def this_may_fail
  some_logic rescue nil
end

you can then use the if modifier to check the return value of your method and assign the value only if it's 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 to call the method twice for the if condition and assignment.

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

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

rubiii
+3  A: 

The problem is precedence. The simplest solution:

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

Changing the precedence like this is a little esoteric, though. It would probably be better if you can rewrite your a_function_that_may_fail to return nil if it fails.

You could also use a temporary variable and test for nilness:

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

A really minor difference is that this does not set post['Caption'] if a_function_that_may_fail did not raise an exception but returned nil.

molf
(...) rescue nil is not that esoteric, imho. It's easy to read too.
Marc-André Lafortune
+2  A: 
post.store('Caption', a_function_that_may_fail) rescue nil
Firas Assaad
Cute, but won't apply if instead of post['Caption']= it was local_var=. I much prefer molf's "esoteric" solution
Marc-André Lafortune