tags:

views:

31

answers:

3

Say I want a call to be run, and if it fails, it's no big deal; the program can continue without a problem. (I know that this is generally bad practice, but imagine a hypothetical, quick one-off script, and not a large project)

The way I've been taught to do this was:

begin
  thing_to_try
rescue
  # awkward blank rescue block
end
next_thing

Of course, there are other ways to do this, including using ensure and things like that. But is there a way to get a method call/block to silently fail without a messy blank block?

+3  A: 

It's the same idea, but a little less verbose, but you can use inline syntax

thing_to_try rescue nil
next_thing
Ben Hughes
This is probably the most concise and useful for a short script; it's the one I'm actually using for my current situation =) But the other answer seems more elegant for projects in the future that I might want this in somehow.
Justin L.
A: 

In addition to Ben's idea, you can also create a function for that

def suppress_errors(&block)
  begin
    yield
  rescue
    # awkward blank rescue block
  end
end

# call it    
suppress_errors {puts "abc"}
suppress_errors do
  puts "xyz"
end
Nikita Rybak
+3  A: 

A method like this can be helpful.

def squelch(exception_to_ignore = StandardError, default_value = nil)
  yield
rescue Exception => e
  raise unless e.is_a?(exception_to_ignore)
  default_value
end

You might define this method inside class Object for universal availability.

Then you can write:

squelch { foo } || squelch { bar }

The real advantage to having this approach is you can use multiline blocks, since inline rescue can only be used on a single statement.

wuputah
Out of curiosity, does your sample usage also act as a begin/rescue?
Justin L.
@Justin L.: Not sure if this answers your question, but there is no `begin` because I am rescuing the entire method call of `squelch`. To put it another way, the `def` keyword is an implicit `begin`.
wuputah
I mean, your `squelch { foo } || squelch { bar }`; does it act the same way as `begin foo; rescue bar; end` ?
Justin L.
No, it's the same as `begin foo; rescue; begin bar; rescue; end; end` (which is really confusing to write in one line!)
wuputah