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?
A raised exception can be rescued to prevent it from crashing your application once it reaches the top of the call stack. In Ruby, we use the rescue keyword for that. When rescuing an exception in Ruby, you can specify a specific error class that should be rescued from.
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 .
It's the same idea, but a little less verbose, but you can use inline syntax
thing_to_try rescue nil
next_thing
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With